在我的这部分代码(接收时间)中,我有一个动态大小的字符数组。这是一个学校项目,需要动态大小的数组。
char* msgtime::getTime() {
std::string t;
t.append(std::to_string(hour));
t.append(":");
t.append(std::to_string(minute));
char *charTime = new char[t.length()];
strcpy(charTime, t.c_str());
return charTime;
}
但是,我无法删除 charTime,因为我正在返回值。我尝试按照我在此处看到的另一个问题将其返回到主程序中的 char* 中,然后在完成后将其删除。此处的代码是函数返回的内容:
void receive(packet &data, SOCKET con) {
msgtime tim;
cout << "Receiving data" << endl;
int in = recv(con, (char*)&data, sizeof(data), 0);
cout << "Data received: " << in << endl;
tim.updateTime();
char *newTime = tim.getTime();
strcpy(data.time, newTime);
delete[] newTime;
}
除非我运行它时出现此错误:
检测到堆损坏:在 0x00129330 处的正常 block (#183) 之后 CRT 检测到应用程序在堆缓冲区结束后写入内存。
我需要删除 getTime 函数中的 charTime 来堵住内存泄漏,但我不知道该怎么做。非常感谢任何帮助!
最佳答案
您没有分配足够的空间,需要多一个字符来存储空终止符:
char *charTime = new char[t.length() + 1];
关于c++ - 从函数中删除动态大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44598045/