-2
int x = 2;
int* ptr = &x;
free(ptr); //why is this an undefined behavior

free will deallocate the memory. here *ptr holds the address of x. Now if it free(ptr) the ptr pointing to x is no more. But iam having confusion if this is not a right approach

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
MAMTHA SRI
  • 31
  • 3

3 Answers3

2

To use free(), it is important to only free items which have come from malloc() or calloc() (or reprocessed by realloc()). Those (along with free()) manage the heap.

int *p = malloc (5620);   /* allocate 5620 bytes */

   /* do something with memory at p */
   ....

free (p);

While other pointers match the data type of free() that is not sufficient. To free a pointer not from malloc() is practically guaranteed to cause serious trouble: immediately crashing the program, introducing a subtle bug which causes weird results later, or clobbers something unrelated.

The heap is one or more areas of the process's memory which provides space to dynamically allocate many types and instances of objects. Those areas do not have to be associated to a particular program variable; linked lists, trees, graphs, and other data structures are naturally held in the heap.

H.S.
  • 11,654
  • 2
  • 15
  • 32
wallyk
  • 56,922
  • 16
  • 83
  • 148
1

x here is defined on the stack, not the heap. you didn't allocate the memory explicitly with malloc or related functions, so there's no need to free.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 2
    Not only is there no need to `free`, attempting to `free` it has undefined behavior (is likely to mess up the implementation's internal data structures). – Keith Thompson Aug 27 '19 at 01:21
0

In C, objects can have automatic ("stack"), static (global), thread-local, or allocated storage. The last type, allocated storage, is obtained by malloc and its lifetime is not tied to execution of a particular block/function (one instance per live call), the lifetime of a thread (one instance per live thread), or global (one instance, period), but rather lives until you explicitly deallocate it by passing a pointer to it to free. The free function can only be used with objects having allocated storage; passing any other pointer to it yields undefined behavior. And passing pointer to other types of objects would not make sense, as their lifetimes are bound to other things and cannot be arbitrarily ended.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711