DEV Community

Discussion on: Dynamic memory allocation in C

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