I would like to use the tool "top" to analyze the memory consumption and possible memory leaks of a process. For this I have written this program (program-name: memoryTest):
int main(){
char* q;
for(int i=0; i<100; i++){
q = (char*) malloc(1024);
sleep(1);
}
return 0;
}
With top I can now watch this program, by filtering with the option "o" and the filter specification "COMMAND = memoryTest" after the said process, however I see no change in the memory consumption of the process. Do I have a stupid mistake here?
Try the following:
for different values in the for loop.
The issue here is Linux doesn't necessary use memory even if it's allocated until it's actually populated. Therefore you need to write data to what you're allocating else it might not even register that that memory is in use. This is why some applications can allocate memory and it's fine, then even when they have allocated, when they come to use the memory, they can find that the memory isn't available.
The memset will force writes of zeros into the allocated buffer, thereby causing the memory to be used and register as being used in top. Note that htop may be easier for you to use here.
If you want to follow up further look into "optimistic malloc" which is a Linux characteristic, note that some other operating systems do not behave this way.
Also it's worth pointing out that internally memory is allocated in contiguous chunks of a certain size. So allocating, say an additional 1KB may not register a size increase if the memory is allocated in minimal block size of say 4k.