¿Por qué obtengo una afirmación de depuración fallida block_type_is_valid cuando elimino este carácter *

 int main(void) {
    const char* kung = "Foo";

    delete []kung;
}

In this piece of code, why do I get the following debug assert failed block_type_is_valid ?

Is it because kung pointer is pointing to a constant string in the memory which cannot be de-allocated ?

preguntado el 29 de julio de 12 a las 22:07

1 Respuestas

Because you can't delete a string literal (which is what kung puntos a).

You also can't delete an automatic-storage string (so it's not really the literal part):

char kung[] = "Foo";
delete []kung;   //still illegal

Solo delete[] memoria que asignas con new[].

Respondido 29 Jul 12, 22:07

@brainydexter yes, but in your example it's even more than that. When you write const char* kung = "Foo";, the string resides in a read-only segment of memory. It's illegal to even modify it, not only the delete. - Luciano Grigore

@Luchian, I agree with your statement, but just to point out a detail, as written, brainydexter's code uses *str++, which due to precedence rules, says, 'advance the pointer, then dereference what is found at the new address'. To invoke the bad behavior, he would need to do '(*str)++'. - Don Wakefield

@brainydexter that's how the language is designed. String literals are located in read-only memory. char* x = "foo" is in read only memory, char[] x = "foo" isn't and you can modify it. - Luciano Grigore

@brainydexter no. String pool is in java. In C++ there can exist multiple identical strings in different places, so it's not a pool. - Luciano Grigore

@brainydexter, Luchian is correct. Some comments on your example code: 'int i' is 'on the stack', meaning local memory for main. The expression 'cout << (*p)++' does a couple of things. One, it dereferences the pointer, getting the value 4 for the stream expression, which is what you see in your terminal. Since you use the post-fix increment, the increment of the temporal integer containing '4' happens después de you stream out the '4', and so is discarded silently. - Don Wakefield

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.