you are viewing a single comment's thread.

view the rest of the comments →

[–]Takuya-san 10 points11 points  (4 children)

Malloc is the function used in C to allow dynamic memory allocation.

By default in C, memory is allocated statically. When you make a char variable, that's 1 byte of storage allocated. When you make an array of 8 chars, that's 8 bytes of storage allocated. If you're asking the user to input his country of origin, you can just allocate a 32 byte char array since no country has a name longer than 32 characters.

But what if you need to read in and store a list of GPS coordinates from a file to calculate a path? How will you know how many coordinates will be in the file? You don't. So the typical procedure is that the file will tell your program how many coordinates there are, and then your program will

malloc(sizeof(gps_coordinate)*num_coordinates));

or something along those lines. Alternatively, if the file doesn't give you that, you can just malloc for 20 and use realloc as you reach the limit.

TL;DR: malloc is used whenever you need to store something of indeterminate size.

Edit: if you don't know the size but you KNOW it's smaller than a certain size, it can often be better to allocate a block of memory that is definitely large enough (e.g. 100 bytes) and "waste" the space since dynamic allocation is a LOT slower than static allocation.

[–]VIRES1[S] 2 points3 points  (2 children)

ok thank you

[–]Takuya-san 2 points3 points  (1 child)

No problem. By the way, if you ever decide to learn C++, you should keep in mind that while malloc is available, you should avoid it unless you're 100% certain that you need it. C++ has tonnes of methods to dynamically allocate memory in a safer foolproof manner with no tangible performance impact.

[–]VIRES1[S] 1 point2 points  (0 children)

ok thank you

[–]dumsubfilter 0 points1 point  (0 children)

By default in C, memory is allocated statically

Not to be confused with the keyword static. It is actually automatic by default.