[英]C++ how to delete local allocated char array?
I wrote a function which receives as a parameter a char pointer,then builds a new dynamic allocated char array that contains that parameter char.Then,it returns the new char array. 我编写了一个函数,该函数接收一个char指针作为参数,然后构建一个包含该参数char的新动态分配的char数组。然后,它返回新的char数组。 This is the function: 这是功能:
char* read_string(char *pstr)
{
char *str;
str = new char[strlen(pstr)];//allocate memory for the new char
str[strlen(pstr)] = '\0';
for(unsigned i=0;i<strlen(pstr);i++)//build the new char
str[i]=pstr[i];
return str;//then return it
}
In main I have: 我主要有:
int main()
{
char *Pchar = read_string("Test");
cout<<Pchar;// Outputs "Test"
delete [] Pchar;//"Program received signal SIGTRAP, Trace/breakpoint trap." error
}
I declare a char pointer in main and then make it point to the char array that is returned from the read_string function.It outputs what I want but if I want to free the memory it gives me runtime error.How can I free up the memory if I don't need to use Pchar anymore? 我在main中声明一个char指针,然后使其指向从read_string函数返回的char数组。它输出我想要的内容,但是如果我想释放内存,它将给我运行时错误。如何释放内存如果我不再需要使用Pchar了吗?
EDIT:Thank you all for your very informative answers.I have successfully resolved the problem. 编辑:谢谢大家提供的非常有帮助的答案。我已经成功解决了这个问题。
Your specific problem is an off-by-one error: 您的特定问题是一个错误的错误:
str = new char[strlen(pstr) + 1];
// ^^^^ need one more for the '\0'
str[strlen(pstr)] = '\0';
Generally, since this is C++ and not C, it would be better to return a smart pointer so the caller knows what the ownership semantics of the pointer are: 通常,由于这是C ++而不是C,因此最好返回一个智能指针,以便调用者知道该指针的所有权语义是:
std::unique_ptr<char[]> read_string(char *pstr)
{
std::unique_ptr<char[]> str(new char[strlen(pstr) + 1]);
// rest as before
return str;
}
您需要分配更多的内存以为EOS字符留出空间:
str = new char[strlen(pstr)+1];
It seems that the error occurs due to incorrect length of the allocated string. 似乎是由于分配的字符串的长度不正确而发生了错误。 You have to use the following record to allocate the string 您必须使用以下记录来分配字符串
str = new char[strlen(pstr) + 1];//allocate memory for the new char
str[strlen(pstr)] = '\0';
The function can look the following way 该函数可以如下所示
char* read_string( const char *pstr )
{
char *str;
size_t n = strlen( pstr );
str = new char[n + 1];//allocate memory for the new char
strcpy( str, pstr );
return str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.