/* 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?
Undefined behavior. It may not fall. The compiler does little weather here.
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; } ... // закончили работу программы
Source: https://ru.stackoverflow.com/questions/2646/
All Articles