William Everett
William Everett

Reputation: 781

Do I understand the memory problems with this malloc/free combo?

I have a c function that looks like this

void fn(void *data) {

    type *p=malloc(sizeof *p);
    p=data;
     ...
    free(p);
}

If I understand correctly, the two problems with this are that the malloc sets aside some memory for p, but the pointer in p is then immediately overwritten by the pointer data so nothing is pointing to the memory allocated to p. Also, the subsequent free actually frees the memory at data so that whatever function called fn will no longer be able to safely access it. Is this right?

What I probably meant to do is:

void fn(void *data) {

    type *p;
    p=data;
     ...
}

Since there's no malloc there's nothing to free and the pointer in data continues to point to allocated memory?

EDIT: I should point out that I know for sure that the pointer in data is actually a pointer of the same type as p.

FURTHER EDIT: The pointer in data points to something that was malloc'd elsewhere.

Upvotes: 0

Views: 83

Answers (2)

haccks
haccks

Reputation: 106022

Yes. You understood right. Assigning data to p after allocating memory to p will leave no pointer to the allocated memory by malloc.
A block of memory that's no longer accessible to a program is said to be garbage. A program that leaves garbage behind has a memory leak.
Unfortunately, unlike some other languages, C doesn't have garbage collector.

Another thing is that calling free(p) will invoke undefined behavior because the argument to free must be a pointer that was previously returned by a memory allocation function (or it could be a NULL pointer).

Upvotes: 3

Wojtek Surowka
Wojtek Surowka

Reputation: 20993

Yes, the function should not free the memory it did not allocate. The principle worth following in most cases is: do not allocate and deallocate in different contexts.

Upvotes: 2

Related Questions