DEV Community


Discussion on: I'm an Expert in Memory Management & Segfaults, Ask Me Anything!

codevault profile image
Sergiu Mureşan

That's a really nice feature, didn't know about it.

But wouldn't that mean data loss in case the memory can't be resized? Wouldn't that become an unrecoverable error?

Thread Thread
codemouse92 profile image
Jason C. McDonald Ask Me Anything

@liulk Ha, I completely forgot to mention Clang! It does indeed have the best warnings of any compiler I've used. I almost always compile with -Wall -Wextra -Wpedantic -Werror; that last one (as you know, although the reader might not) causes the build to fail on any warnings.

I also use cppcheck as part of my autoreview workflow, and resolve all linter warnings before committing to the production branch.

Thread Thread
liulk profile image
Likai Liu

@codevault You're right, reallocf() would just free the memory and cause data loss, so it would serve a different use case than realloc(). The more general solution would be to always use this pattern, which is more verbose:

void *q = realloc(p, new_size);
if (q == NULL) {
  // do error handling.
p = q;

I just find that in most of my use cases, I would end up freeing p in the error handling, so I would just use reallocf() which results in less verbose code.

Thread Thread
codevault profile image
Sergiu Mureşan

I see, that makes sense. I can see myself freeing the memory most of the time when reallocation fails.

Good to note. Thanks!