eugen-fried
eugen-fried

Reputation: 2173

How to free a returned malloced string?

I have the following two functions. Function get_string_data(line) mallocs a string and returns it. Later I use it like this:

char *get_string_data(char *) {
    char *sec_tok, *result;
    Split *split;
    split = split_string(line, ' ');

    sec_tok = split -> tail;

    if (starts_with_char(sec_tok, '\"') && ends_with_char(sec_tok, '\"')) {
        result = (char *) malloc(strlen(sec_tok) + 1);
        strcpy(result, sec_tok);
        free(split);
        result++;
        *(result + (strlen(result) - 1)) = '\0';
        return result;
    }
    free(split);
    return NULL;
}

void handle_string_instr(char *line) {
    char* data = get_string_data(line);

    ...a few lines later, after I used the data...

    free(data);
    ... end of the world happens here...
}

Now on attempt to free the string everything crashes (Program received signal SIGABRT, Aborted.). Why does this happen, and what is the correct way to free the memory?

Upvotes: 0

Views: 653

Answers (2)

JaredPar
JaredPar

Reputation: 754575

Here is the problem code

result = (char *) malloc(strlen(sec_tok) + 1);
...
result++;
...
return result;

At this point the get_string_data method is no longer returning a pointer to the memory that was allocated. It is instead returning a pointer into the memory that was allocated. You can only pass pointers to memory that was allocated to free. In this case you don't and this is why it is crashing

Also a simpler way of null terminating the string would be the following

size_t length = strlen(sec_tok);
result = (char*)malloc(length + 1);
...
result[length] = '\0';

Upvotes: 5

Scotty Bauer
Scotty Bauer

Reputation: 1277

free(line) get_string_data possibly moves the pointer to some location in "line" which is not the correct pointer to return to free().

Upvotes: 1

Related Questions