ALOToverflow
ALOToverflow

Reputation: 2699

Correct way to free memory

Makes a while since I've done some C and I have to refresh my understanding of pointers. Here is a function that modifies the content of a pointer. The question is if this code is correct. Is it enough if I only free the pointer or do I have to free the content of by the pointer

void foo(char **str) {
   // str has been allocated enough bytes for the following text
   *str = "allocate some text";
}

int main(int arc, char *argv[]) {
    char *someString;
    foo(&someString);
    free(someString); // is this the correct place to free
}

Thank you.

Upvotes: 3

Views: 301

Answers (5)

MByD
MByD

Reputation: 137422

You don't show in your code, but you write that str has been allocated with enough bytes. So that's fine, and can be freeed, but than you assign the pointer to the constant string to str - *str = "allocate some text"; (and as oli said, causes undefined behavior on free) instead perform strcpy():

strcpy(str, "allocate some text");

Upvotes: 1

Simone
Simone

Reputation: 11797

There's something that puzzles me in this code.

Why the comment says "str has been allocated enough bytes for the following text "? Even if it has been allocated, you are assigning to the pointer a new value, so it doesn't buy you anything having allocated that memory.

Anyway, according to this code, free() shouldn't be called.

Upvotes: 1

Osiris76
Osiris76

Reputation: 1244

First the call of the method foo should be adjusted, since the parameters don't match. It should look something like

foo(&someString);

But personally I would agree to the place where you called the method free(someString). Because the application is about to end and you no longer need any pointer.

Upvotes: -2

James
James

Reputation: 25543

You shouldn't free at all in this case. free() should always correspond to a call to a malloc() function.

Here you are 'freeing' constant memory that was never allocated in the first place.

Upvotes: 2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272717

No, you don't want to call free(), because you never malloc()-ed the data. More specifically, calling free() on a pointer to a string literal results in undefined behaviour.

Upvotes: 10

Related Questions