Overview
This post deals with pointers because dynamic memory allocation only works with pointers.
Whenever you define a variable in C, ...
For further actions, you may consider blocking this person and/or reporting abuse
Casting the result of malloc is unnecessary and very bad practice.
Bad:
Good:
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.
stackoverflow.com/a/605858/9815377
It's important to stress that we're talking about C, not C++
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...)
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.
Can you elaborate and/or provide an example of what is considered best practice?
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.
Thanks! These are my notes as I learn the language, so comments and clarifications like this are most welcome 😀👍
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
You probably meant on the stack here.
I did, thanks for the catch!