If I say:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char *x;
char *y;
int main() {
x = malloc(sizeof("Hello, world!"));
strcpy(x, "Hello world!");
y = "Hello, world";
free(x);
fprintf(stderr, "okay");
free(y);
}
Then, obviously, the program will print “okay” followed by dying because the “pointer being freed was not allocated”—obviously, because the string was a string literal.
I’d like to write a function that does nothing when given string literals, but calls free when given non-string literals. Is that possible, and if so, how?
No. In C, you have to keep track of what you’ve allocated yourself.
Some
mallocimplementations (such asdlmalloc) provide some extra functionality for inspecting the heap, but you shouldn’t rely on those.dlmallochas the functiondlmalloc_inspect_all, which will walk the heap and return to you all of the regions of memory thatmallochas allocated, except for memory-mapped chunks. So you could use that to test if a pointer points to a non-memory-mapped allocation, but it’s still a bad idea in general.And on Windows, don’t even think about using [
IsBadReadPtr] to test if a pointer points to readable memory or not — it should really be calledCrashProgramRandomly.