Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Free an assigned pointer

Tags:

c

free

Does the following code free the memory that was allocated for x?

int main()
{
    char *x = (char*)calloc(100, sizeof(char));
    char *y = x;
    free(y);
}
like image 418
cxphong Avatar asked May 01 '15 10:05

cxphong


People also ask

What does it mean to free a pointer?

Freeing the allocated memory deallocates it and allows that memory to be used elsewhere while the pointer to where the memory was allocated is preserved. Setting a pointer to the allocated memory to NULL does not deallocate it.

How do you free the memory of a pointer?

C library function - free() The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

Can I use a pointer after freeing it?

Yes, when you use a free(px); call, it frees the memory that was malloc'd earlier and pointed to by px. The pointer itself, however, will continue to exist and will still have the same address.

How do you free an object in C++?

C++ free()The free() function in C++ deallocates a block of memory previously allocated using calloc, malloc or realloc functions, making it available for further allocations. The free() function does not change the value of the pointer, that is it still points to the same memory location.


2 Answers

Yes

When you do

char *y = x;

you make y point to the location where x points to. Since y points to a memory location returned by calloc,

free(y);

is perfectly valid. As @haccks commented, this would not work if you make y point to another memory location, provided that this memory location wasn't returned by malloc/calloc/realloc.


In C, you should not cast the result of malloc/calloc/realloc. Also, checking the return value of calloc to see if it was successful is good. calloc will return NULL on failure.

like image 172
Spikatrix Avatar answered Sep 22 '22 08:09

Spikatrix


The original version of the question had

int *y = x;
free(y);

I.e. assigning the char pointer to an int pointer and then invoke free() on the int pointer. The signature of free() is void free(void *ptr); so irrespective of char * vs. int *, memory would be released.

The edited (and current) version of the question has

char *y = x;
free(y);

Here, both y and x points to the same memory. This is known as pointer aliasing. Upon the call to free(), that memory would certainly be released.

A problem, however, is that after free(y), the pointer x would be dangling, i.e. the memory it is pointing to is no longer valid.

Note, it is neither necessary nor recommended to cast the return value from calloc.

like image 42
Arun Avatar answered Sep 22 '22 08:09

Arun