malloc and memory

I usually stay away from using malloc for memory issues but then I thought:

b = (char*) malloc(2);
char b[2];

Is the above any different than the bottom in terms of memory?

Yes, they are different. It depends on the calling context. In the first, the pointer might go out of scope at the end of the function call, but the object you malloc'ed remains.

In the second, the whole thing can go out of scope and disappear when you're done with it.

If you are talking about a global or something that only gets created once in the program then there's not as much difference.

mistergreen: Is the above any different than the bottom in terms of memory?


Dynamically allocated memory stores a header before the allocated (usable) memory. The header stores the length of the allocation. free() uses this header by subtracting a predefined number of bytes from the pointer passed to free(), it accesses the header and frees the set amount of bytes.

The reason dynamic memory is slow is because it is a 'run length' algorithm. Each allocation requires traversing the headers to find a free chunk of memory.

A bit of a side step, but overall, yes, dynamic memory uses more RAM than statically allocated memory on a per allocation basis.

Also, autos that go out of scope come off the stack, while malloc’d objects come off the heap. Objects on the stack don’t contribute to memory fragmentation.

Ah thanks. So if this malloc is in a function that gets called so often, the memory would just pile up unless you ‘delete’ or free().

Even freeing can be a problem, since, depending on the allocations you have made, it can leave areas in memory that cannot be re-used. This is called memory fragmentation.