简体   繁体   English

指定的存储位置中没有指针。 Delete op有什么问题?

[英]No pointer in the specified memory location. What's wrong with delete op?

I am trying to make an example for char pointers and use of delete operator. 我正在尝试为char指针和使用delete运算符创建一个示例。 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. 我知道nameptr从输出中指出位置0xbf9e4184。 There is no pointer points out to that location (0xbf9e4194). 没有指针指向该位置(0xbf9e4194)。 I believe it's something to do with my use of delete but I couldn't figure it out. 我相信这与我使用delete有关,但我无法弄清楚。

You should only call delete or delete [] on memory allocated with new or new [] , respectively. 您只应分别在分配有newnew []内存上调用deletedelete [] There's no need to free string literals like "subject" . 无需释放诸如"subject"类的字符串文字。

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[]使用new[]分配的内容 (实际上, name 使用new[]分配,您未编写: 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 ). 因此,(正确)检测到一个错误,因为您尝试使用new (或malloc )释放堆中未分配的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM