Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C malloc, memory usage only when populating

I'm allocating some space with malloc when my app starts. If I don't populate this variable top shows 0% of my memory used by this app, but if I start to populate this variable top begins to show increase usage of ram by the way I'm populating this array.

So my question is: shouldn't top show this space allocated by malloc as an used space of my app? Why it only show increase of RAM usage from my app when I populate this variable?

I'm at Ubuntu 10.10 64bits. Here is the code that populates it:

char pack(uint64_t list, char bits, uint64_t *list_compressed, char control, uint64_t *index){
uint64_t a, rest;   

if(control == 0){
    a = list;
}
else{
    rest = list >> (64 - control);

    a = (control == 64 ? list_compressed[*index] : list_compressed[*index] + (list << control));

    if(control + bits >= 64){
        control = control - 64;
        //list_compressed[*index] = a;
        (*index)++;
        a = rest;
    } 
}

//list_compressed[*index] = a;
control = control + bits;

return control;
}

The "malloqued" variable is list_compressed.

If I uncomment the list_compressed population the ram usage is increased, if I keep it commented the usage is 0%.

like image 773
Frederico Schardong Avatar asked Feb 21 '23 18:02

Frederico Schardong


1 Answers

Short answer, no. On many OSs, when you call malloc, it doesn't directly allocate you the memory, but only when you access it.

From malloc man page:

By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available.

like image 145
MByD Avatar answered Feb 23 '23 06:02

MByD