Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing pointer after pointer arithmetic

My question is very simple one. Say we have:

char* ptr = (char*) malloc(sizeof(char)*SIZE);
ptr+= SIZE/2;
free(ptr);

What happens when we free the pointer? Is it undefined operation? Does it free all of SIZE buffer or only the remaining SIZE/2? Thanks in advance for disambiguating this for me.

like image 490
Lefteris Avatar asked May 16 '11 06:05

Lefteris


People also ask

Can you 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.

What does freeing a pointer do?

The function free takes a pointer as parameter and deallocates the memory region pointed to by that pointer. The memory region passed to free must be previously allocated with calloc , malloc or realloc . If the pointer is NULL , no action is taken.

What are the rules for pointer arithmetic?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

What is pointer arithmetics?

Address arithmetic is a method of calculating the address of an object with the help of arithmetic operations on pointers and use of pointers in comparison operations. Address arithmetic is also called pointer arithmetic.


2 Answers

Your program will probably crash: the free() operation is actually quite simple in C, but works only on the original allocated address.

The typical memory allocator works like this pseudo code:

  • ask to alloc 64 bytes
  • allocator allocs 70 bytes (6 bytes more)
  • the first 2 bytes is set to a "signature", a pattern recognized by the allocator to identify the memory allocated by him
  • the next 4 bytes denote the allocated size
  • return a pointer to the start of the 7th byte

So when you call free(ptr), the allocator goes 6 bytes before your pointer to check for the signature. If it doesn't find the signature, it crashes :)

like image 147
Gui13 Avatar answered Sep 18 '22 00:09

Gui13


If the argument to free() does not match a pointer previously allocated by means of malloc() and friends, the behaviour is undefined. You will most likely encounter a segmentation fault or a failed assertion in your version of libc.

Offtopic: it's better you didn't cast the result of malloc() in C.

like image 28
Michael Foukarakis Avatar answered Sep 18 '22 00:09

Michael Foukarakis