Operation of the delete operator in C ++


I do not understand how the delete operator works in this function since std::cout << datosCli[0] << '\n'; , which is executed after delete[] datosCli; , continues to print the String on the screen. Should not you lose the reference to the contents of the array after calling delete[] ?

string * Taquilla::genDatosCliente(){

 string nombres[] = {"Sergio","Ernesto","Julio","Fabio","María","Laura","Manolo","Luisa",
                 "Jose","Eva","Azucena","Samuel", "Gandalf"};

 string apellidos[] = {"Salaices","Oliva","Garcia","Fuentes","Merino","Robles","Lifton","Redondo",
                   "Rivas", "Fuerte","Muñoz","Blanco","Calvete","Moreno","Dominguez","Martinez",

 char letraDNI[] = {'T','R','W','A','G','M','Y','F','P','D','X','B',

 // Semilla del Random

 // Obtención de los datos del cliente mediante los índices generados
 // aleatoriamente.
 string nombre = nombres[rand()%((sizeof(nombres))/(sizeof(nombres[0])))];
 string apellido1 = apellidos[rand() %((sizeof(apellidos))/(sizeof(apellidos[0])))];
 string apellido2 = apellidos[rand() %((sizeof(apellidos))/(sizeof(apellidos[0])))];

 string *datosCli = new string[4];

 datosCli[0] = nombre;
 datosCli[1] = apellido1;
 datosCli[2] = apellido2;

 int numDNI = 10000000 + rand() % (99999999-10000000);
 datosCli[3] = to_string(numDNI) + letraDNI[numDNI%23];

 delete[] datosCli;
 std::cout << datosCli[0] << '\n';

 return datosCli;
asked by Álvaro García Merino 30.10.2018 в 23:56

2 answers


Using an object after having done delete is an undefined behavior (in English, undefined behavior , often written as UB ).

And what about indefinite behavior? Well, as its name suggests, it is not defined.

Like the program works as expected. Likewise, the program aborts and ends, with an error. The same sends an email to your boss. In three words:


You can not expect the observed behavior to remain constant if you change the compiler, or you touch a single line of program code, even in different executions.

In particular, the delete the only thing that has to do is to call the destructor of the object and mark the memory it occupied as "free". You do not have to put that memory to zero, or make the variable point to another memory location.

As the programmers are boring people who like the programs to behave as we expect without surprises, avoid UBs even if it seems to "work".

More information on indefinite behavior , not specified and defined by the implementation

answered by 31.10.2018 / 01:50

Although it may not seem like it, C ++ does not take care of memory management, that's what the Operating System (OS) handles. What C ++ does is inform the OS of the memory it needs and also inform when it has stopped using such memory; with this information the OS (not the programming language) manages the memory.

Imagine that you are going on a trip, you stay in a nice hotel, before you sleep, you read a book for a while and when your sleep expires you leave it on the bedside table. The next day you pack your bags and go to the station of your favorite means of transport but forget the book !. Nothing happens! You still have time to go back and get it back! You run to the hotel, return to your room and find the book there, thank goodness!

But just a moment! Are not rooms supposed to be cleaned when the guest leaves? How is it possible that the book is still there when the room should have been cleaned?


Should not the reference to the contents of the array be lost after calling delete[] ?

Should not the content of the hotel room be lost after checkout?

No, the hotel staff can take care of the room you were using when it suits them; and this does not have to be after your checkout if not at any other time.

The same happens with the OS and memory management: the OS can take care of the memory you were using when it suits you; and this does not have to be after your delete[] if not at any other time. Moreover, the OS can decide to mark the memory as available but without modifying its content; In this way the old data would be present even after deletion!

answered by 31.10.2018 в 11:57