DEV Community

Dynamic memory allocation in C

mikkel250 on December 25, 2019

Overview This post deals with pointers because dynamic memory allocation only works with pointers. Whenever you define a variable in C, ...
Collapse
 
step_prosperi profile image
Stefano Prosperi

Casting the result of malloc is unnecessary and very bad practice.

Bad:

int * pNumber = (int*) malloc(25*sizeof(int));

Good:

int * pNumber = malloc(25*sizeof(int));
Collapse
 
therselman profile image
therselman • Edited

I think you are wrong about casting malloc is bad practice. You will get a compiler warning if you don't! It's total rubbish that it's bad practice! If you are not getting compiler warnings, then you aren't using a high enough warning level! It's more an inconvenience than anything else, that's why C++ created the Auto keyword, but even then you would need to cast it so that auto can infer the correct type.

Collapse
 
step_prosperi profile image
Stefano Prosperi • Edited

stackoverflow.com/a/605858/9815377

It's important to stress that we're talking about C, not C++

Thread Thread
 
ac000 profile image
Andrew Clayton

Indeed.

I think it is also worth explicitly stating that these days C and C++ are very different languages. (All too often I see people conflating the two or just saying C/C++, when they really mean one or the other...)

Collapse
 
eccles profile image
Paul Hewlett

The realloc example, whilst correct, is bad practice. What if realloc fails? In that case you will lose reference to the previously allocated str. The original memory will be orphaned.

Collapse
 
mikkel250 profile image
mikkel250

Can you elaborate and/or provide an example of what is considered best practice?

Collapse
 
eccles profile image
Paul Hewlett

Use a dummy ptr something like this...

Void *ptr = realloc(str, new size)
If (!ptr) {
.... Handle error...
}
str = ptr

This way if realloc fails the reference to str is not lost.

Of course in a normal Linux environment it is rare for any of the allocation functions such as malloc, calloc etc.. to fail. See anything about overcommit for an explanation.. This would make good subject for a followup article.

Thread Thread
 
mikkel250 profile image
mikkel250 • Edited

Thanks! These are my notes as I learn the language, so comments and clarifications like this are most welcome 😀👍

Thread Thread
 
eccles profile image
Paul Hewlett

Pleasure.

You might be interested in how linux actually allocates memory and why the malloc() type functions actually rarely fail.

Google overcommit, oomkiller and page tables.

Might make a good subject for your next blog

Collapse
 
tomlankhorst profile image
Tom Lankhorst

Things such as function arguments and local variables are stored in the heap, and the memory is automatically freed when a function ends.

You probably meant on the stack here.

Collapse
 
mikkel250 profile image
mikkel250

I did, thanks for the catch!