Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you determine if a string if freeable in C? [duplicate]

Tags:

c

malloc

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?

like image 825
Aaron Yodaiken Avatar asked Jun 22 '11 22:06

Aaron Yodaiken


1 Answers

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.

like image 57
Matti Virkkunen Avatar answered Sep 21 '22 23:09

Matti Virkkunen