0
int main()
{
    int* Pointer;

    Pointer = (int*)malloc(sizeof(int));
    *Pointer = 33;

    int * Pointer2 = Pointer;

    printf("%d\n", *Pointer);

    free(Pointer);
    free(Pointer2);

    return 0;
}

the output is: 33 with no errors or warnings. i declered on two Pointers that pointing to same Heap address. i know its worng to free them both and just one free need to be use here (one malloc one free) but if i will do this(free them both), its will be Undefined? or it OK to do that its just wont do anything to free same heap area from diffrent Pointers (Pointer and Pointer2)?

trincot
  • 263,463
  • 30
  • 215
  • 251
  • It's not OK. Maybe nothing will happen or maybe the system will crash. – Fiddling Bits Mar 02 '17 at 15:11
  • @StoryTeller, the question isn't whether the code performs a double free, but what the effect of that is. – John Bollinger Mar 02 '17 at 15:14
  • 1
    @JohnBollinger - The dup I suggested asks the same question in different words. I see no difference between asking "is this undefined" and "is this as bad as directly causing UB". But by all means, suggest a better dup. I doubt there's a shortage of them. – StoryTeller - Unslander Monica Mar 02 '17 at 15:16
  • For safety you should null the second pointer. Depending on the system you could access undefined memory. – Alex Mar 02 '17 at 15:17
  • @StoryTeller, evidently you and I interpret your proposed dupe differently. As far as I can tell, your proposed dupe and all the answers to it are focused tightly on the issue of whether a double free is defined in terms of the *value* of the pointer that is freed, or in terms of the *variable* holding that value. I don't see that as being more than tangentially related to this question, which acknowledges that there is double free, and asks about its *effect*. – John Bollinger Mar 02 '17 at 15:26
  • @JohnBollinger - *"evidently you and I interpret your proposed dupe differently"* Yes it's obvious we are. But I reiterate: please propose a better one, seeing as this question is asked often enough that I found several options and chose poorly. Assuming of course the purpose of this entire debate is to find a good dup, and not to make sure a low hanging fruit is left up for grabs. – StoryTeller - Unslander Monica Mar 02 '17 at 15:30
  • @StoryTeller, very well, done. – John Bollinger Mar 02 '17 at 15:37

1 Answers1

1

As per the C11 standard draft 7.22.3.3p2

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.

(The emphasis is mine..)

Eugene Sh.
  • 17,306
  • 6
  • 34
  • 57