Frage

I am trying to make an example for char pointers and use of delete operator. Code is very simple:

char name[] = "subject";
char *nameptr = name;
cout <<"&nameptr: " <<&nameptr<< endl;
delete [] nameptr;

and I keep getting this error:

*** glibc detected ***  free(): invalid pointer: 0xbf9e4194 ***

and I know nameptr points out to location 0xbf9e4184, from the output. There is no pointer points out to that location (0xbf9e4194). I believe it's something to do with my use of delete but I couldn't figure it out.

War es hilfreich?

Lösung

You should only call delete or delete [] on memory allocated with new or new [], respectively. There's no need to free string literals like "subject".

Andere Tipps

Examine your code statement by statement:

Here you have an array of characters, containing "subject":

char name[] = "subject";

Here you define a pointer, pointing to the aforementioned array:

char *nameptr = name;

Here you delete[] something that you did not allocate using new[] (in fact, name was not allocated using new[], you didn't write: char * name = new char[...]):

delete [] nameptr;

So, an error is (correctly) detected, because you tried to free something that was not allocated on the heap using new (or malloc).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top