2

Is the following code OK to use or not.

int main() {
    int *p = (int *)malloc(sizeof(int));
    int *q = (int *)malloc(sizeof(int));

    free(p);

    free(q);

    if (p==q) {
    //...
    }
}
curiousguy
  • 8,038
  • 2
  • 40
  • 58
  • 5
    This is a famously difficult question. I don't remember the intricate details, but per a strict reading of the Standard, using the value of a pointer after calling free is undefined. This code will work on any "reasonable" system, but I would never write it, in part of the concern about undefinedness, in part because there's no good reason to. – Steve Summit Sep 14 '19 at 14:33
  • @observer, p and q will not change to null. – nicomp Sep 14 '19 at 14:34
  • 1
    Everybody please don't post answers as comments. Comments can't be downvoted which makes it very difficult to separate the accurate and inaccurate comments. As @SteveSummit says this is a famously difficult question. A good answer requires care and precision: it needs a language lawyer. – John Kugelman Sep 14 '19 at 14:44
  • 1
    Anybody: If you don't like the linked question, see also the [C FAQ](http://c-faq.com/) list, [question 7.21](http://c-faq.com/malloc/ptrafterfree.html). – Steve Summit Sep 14 '19 at 14:54

0 Answers0