1

I have written the following code in C:

#include <stdio.h>  
#include <stdlib.h> 
int main (int argc , char *argv[])  {
int * ptr = (int *)malloc(sizeof(int)); 
int three = 3; 
ptr = &three; 
free(ptr);
return EXIT_SUCCESS;
}

When I execute I get following error:

Abort signal from abort(3) (SIGABRT).

Could you help me find my mistake? Thank you!

clearner
  • 81
  • 3
  • 3
    `int * ptr = malloc(...); ptr = &three;` is like doing `int x = 10; x = 5;` and then wondering why `x` is not equal to `10`. With a little [rubber duck debugging](https://en.wikipedia.org/wiki/Rubber_duck_debugging) you should have (hopefully) been able to figure it out yourself. – Some programmer dude Feb 22 '19 at 09:41
  • 2
    You're doing the equivalent of `free(&three)`, which you're not allowed to do. – molbdnilo Feb 22 '19 at 09:43
  • Learn to use [valgrind](http://valgrind.org/) – Basile Starynkevitch Feb 22 '19 at 09:50

2 Answers2

4

What you have is undefined behavior. The C11 standard states thus:

7.22.3.3 The free function
...
2 The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

In your example the argument of free is &three which is not a pointer returned by a memory management function and therefore you have the behavior you see.

P.W
  • 26,289
  • 6
  • 39
  • 76
1

When you call malloc a pointer to memory chunk of requested size is returned (on success). This memory chunk is allocated form heap, and you can use that pointer to un-allocate it by calling free later. Local variables are allocated memory from stack. What you are doing here is allocating a memory chunk from heap:

int * ptr = (int *)malloc(sizeof(int));

and then overwriting then overwriting ptr with address of a local variable who's memory resides on stack.

ptr = &three; 

and then attempting to free that memory:

free(ptr);

which is undefined behaviour.

Sandy
  • 895
  • 6
  • 17