I have a struct
struct request {
int code;
char *message;
};
that I’d like to free properly.
I have the following function to do that:
void free_request(struct request *req) {
if (req->message != NULL) {
free(req->message);
}
free(req);
req = NULL;
}
The problem is that I get an “free(): invalid pointer”/segfault error from the compiler when I try to free a request that has been created using a string literal:
struct request *req;
req = malloc(sizeof(struct request));
req->message = "TEST";
free_request(req);
Since I want to create request structs in different places, once using literals (on the client side) and once using *chars that I read from a socket (on the server side) I was wondering if there is a function to make sure that I don’t try to free the literals while still allowing me to free the message I have created using a malloc.
There is no standard function that lets you know if a pointer was dynamically allocated or not. You should include a flag in your struct to inform yourself of it, or only use dynamically allocated strings (
strdupis your friend in this case). Depending on your networking setup, it might be simpler to usestrdup(well, to tell the truth, it is simpler to use thestrdupat all).With
strdup:With a flag:
Also, don’t forget to zero your allocated memory when you create an object. That could save you a lot of trouble.
That, and setting
reqtoNULLfromfree_requestwon’t have any effect. You either need to take astruct message**or do it yourself after the function calls.