And so, I have two functions, one allocates memory for the structure, the other frees. Well, since I want to avoid problems with the double release of memory, I decided to check the pointer for 'nullity' and reset it after release.

Less words, more code:

#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member))) using Tint = int64_t; using Tuint = uint64_t; using Pint = Tint *; struct Numx { Tuint alen; Tint len; bool sgn; Tint exp, m; Tuint d, reserved[12]; }; // выделяет память и возвращает указатель на 'm' Pint ALLOCX(Tuint len) { if (len == 0) { return nullptr; } Numx *ptr = (Numx *)operator new((len - 1) * sizeof(Tint) + sizeof(Numx)); ptr->alen = len; ptr->len = 0; ptr->sgn = 0; ptr->exp = 1; ptr->d = 1; return &ptr->m; } // через макрос container_of получает указатель на структуры и освобождает память void FREEX(Pint x) { if (x == nullptr) { return; } operator delete((void *)container_of(x, Numx, m)); x = nullptr; printf("%p\n", x); // <= выводит '0000000000000000' } int main() { Pint x = ALLOCX(1); printf("%p\n", x); // <= выводит '000000013F210060' FREEX(x); printf("%p\n", x); // <= опять '000000013F210060' std::cin.get(); return 0; } 

And so, what's the problem? Why does the FREEX () function print zeros, and right after it does not?

Closed due to the fact that off-topic participants AnT , 0xdb , LFC , freim , aleksandr barakin 16 Feb at 18:16 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • "The question is caused by a problem that is no longer reproduced or typed . Although similar questions may be relevant on this site, solving this question is unlikely to help future visitors. You can usually avoid similar questions by writing and researching a minimum program to reproduce the problem before publishing the question. " - AnT, 0xdb, LFC, freim, aleksandr barakin
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    +1 for the word "uzatel" - Igor
  • Stupid mistake x2 :) - complex
  • It is precisely this moment that illustrates the general uselessness of the idea of ​​dealing with the "problem with double release of memory" by zeroing the pointer. Pointers and you at least one thousand may point to the same memory area. From the fact that you zero one of them, the rest will not change. And the danger of a double release of memory will not disappear anywhere. - AnT pm
  • @AnT Well, at least one and the same pointer will not be released twice. And the release of another pointer to the same memory is already unclear how to avoid - complex

1 answer 1

 void FREEX(Pint& x) { ... 
  • Hmm, quite a silly mistake, thank you - complex
  • @complex On health. Successes! - Igor