Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is malloc necessary in C?

Tags:

c

malloc

I think all malloc(sizeof(structure)) can be replaced this way:

char[sizeof(structure)]

Then when is malloc necessary?

like image 408
wamp Avatar asked Oct 08 '10 09:10

wamp


1 Answers

  • When you don't know how many object of some kind you need (e.g. linked list elements);
  • when you need to have data structures of size known only at runtime (e.g. strings based on unknown input); this is somewhat mitigated by the introduction of VLAs in C99, but see the next point:
  • when you know at compile time their size (or you can use VLAs), but it's just too big for the stack (typically a few MBs at most) and it would make no sense to make such thing global (e.g. big vectors to manipulate);
  • when you need to have an object whose lifetime is different than what automatic variables, which are scope-bound (=>are destroyed when the execution exits from the scope in which they are declared), can have (e.g. data that must be shared between different objects with different lifetimes and deleted when no one uses it anymore).

Notice that it isn't completely impossible to do without dynamic memory allocation (e.g. the whole rockbox project works almost without it), but there are cases in which you actually need to emulate it by using a big static buffer and writing your own allocator.

By the way, in C++ you will never use malloc()/free(), but the operators new and delete.


Related: a case in which trying to work without malloc has proven to be a big mess.

like image 187
Matteo Italia Avatar answered Oct 04 '22 06:10

Matteo Italia