/* C */ int *p = (int *)malloc(size); free(p); free(p); // C++ int *p = new int[size]; delete[] p; delete[] p; 

Should the code obviously fall or does it depend on the compiler?

    2 answers 2

    Undefined behavior. It may not fall. The compiler does little weather here.

    • In debug mode, there is likely to be some kind of intelligible error. In the release - wait for anything :). Of course, it depends on the compiler \ environment. But in any case, this can not be done. - kirelagin
    • I would say from the runtime environment - in the sense of Windows (which one), Unix (which one). They all react differently to poor handling of the heap. - andruxa
    • Almost certainly it will fall (especially if there is malloc () between free (), unfortunately, it usually does not fall right away on the second free (), but somewhere on the next malloc (). - avp
    • "Almost certainly it will fall (especially if there is malloc () between free (), unfortunately, it usually does not fall right away on the second free (), but somewhere on the next malloc ()." aha - on the second alloc. - Denis
    • one
      It would be surprising if it even fell in release, even in debug :). The standard ensures that deleting a null pointer is a safe operation. - kirelagin

    Sishny - will fall almost certainly. Because malloc, when allocating memory, writes service information to the beginning of the allocated block, and then free uses this information.

    With ++ the code will crash too, but it seems to me that it can throw an exception, and even better, stuff everything into try-catch blocks :-)

    Better yet, follow the agreement - all pointers initialize NULL and when they are deleted also make them NULL, ie:

     int *ptr = NULL; ... ptr = (int*)malloc(size); // приведением затыкаем рот компилятору if (ptr == NULL) { // ошибка! сделайте что-нибудь. } ... if (ptr!=NULL) { free(ptr) //иначе ptr уже убит и делать ничего не надо ptr = NULL; } ... // закончили работу программы 
    • 2
      try..catch probably will not help either. just before deleting (in any case, delete), it makes no sense to check the pointer to null. For some, these checks turn into a pathological habit, and then the whole code is replete with them. as far as possible it is better to use smart pointers - alphard
    • Smart pointers - yes, a good idea. Using C ++ use STL and Boost? :-) <i> just before deleting (in any case, delete) it makes no sense to check the pointer to null. </ i> <pre> delete p; p = NULL; delete p; </ pre> does not fall on the second delete <pre> delete p; delete p; </ pre> falls :-( - gecube
    • one
      Here is the meaning: if (ptr! = NULL) {delete ptr; ptr = NULL; } - alphard
    • But I didn’t say the opposite :-) try / catch doesn’t work along the way - gecube