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?
I don't think the standard has anything for checking whether a pointer was returned by malloc or not (and you're only supposed to pass those to free) so I'd say no, you can't find that out. You'll have to keep track of it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With