DEV Community

loading...

Discussion on: Dynamic memory allocation in C

Collapse
mikkel250 profile image
mikkel250 Author

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 Author • 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