-2

I am asking the above stated weird question to only improve my understanding about dynamic memory allocation.

In addition to above question I run the following code snippet on codepad.org.

void main()
{
   static int a = 10;
   int* b = &a;
   free(b);
}

I am getting "Segmentation fault" message on output window.What is this?May be I am accessing restricted memory through free()?

Also If a don't Initialize 'a' then Nothing is displayed on output window. Please help me out understanding this behavior.

Vagish
  • 2,520
  • 19
  • 32
  • what is your objective? What would you expect to happen? – Picarus Jun 04 '14 at 13:01
  • 3
    It is called "undefined behavior". – Vaughn Cato Jun 04 '14 at 13:01
  • Why down vote?I Searched a lot trying various combinations,the linked question didn't pop up.Is the asked question is wrong?Why discourage peoples by down voting?Is it my fault that I cant come up with word combinations that previous question has? – Vagish Jun 05 '14 at 04:34

1 Answers1

3

You get undefined behavior, since you're passing a pointer to free() that was not acquired by malloc() (or one of its sibling heap allocations functions, like realloc() & co).

Of course free() can't know this, and avoid treating the pointer as if it were valid. Thus, it will assume it can find whatever book-keeping data it needs associated with the pointer, in whatever way was chosen by your particular memory allocator implementors.

Note that there is nothing "magic" about free(), it's just a function. In particular, it doesn't have access to any more information than that which is passed in, i.e. a single pointer.

unwind
  • 391,730
  • 64
  • 469
  • 606