检测到的堆损坏,同时删除动态的2D char数组
我已经写了一个名为Visa的Char **班级字段(这是动态的2D阵列)(基本上我希望有一个人访问过的国家)和国家 /地区(实际上是数组的大小)。我故意不使用字符串。我添加了一种类方法,该方法将国家添加到上述数组中,但是当我尝试删除数组元素时,我发现了堆损坏:在正常块之后(#158):
void ForeignPassport::addCountry(const char* country) {
char** tmp = new char* [countriesVisited + 1];
for (int i = 0; i < countriesVisited+1; i++) {
tmp[i] = new char[strlen(country)];
}
for (int i = 0; i < countriesVisited; i++) {
int f = 0;
while (visa[i][f-1] != '\0') {
tmp[i][f] = visa[i][f];
f++;
}
}
for (int i = 0; i <= strlen(country); i++) {
if (i == strlen(country)) {
tmp[countriesVisited][i] = '\0';
break;
}
tmp[countriesVisited][i] = country[i];
}
countriesVisited++;
for (int i = 0; i < countriesVisited-1; i++) {
delete[]visa[i];
}
visa = tmp ;
}
I have written a class with char** class field(which is dynamic 2d array) named visa(basically i want there to be countries which a person has visited) and countriesVisited(in fact size of the array). I intentionally didn't use strings. I've added a class method, which adds countries to the mentioned array, but when i try to delete the array elements i get HEAP CORRUPTION detected: after Normal block (#158):
void ForeignPassport::addCountry(const char* country) {
char** tmp = new char* [countriesVisited + 1];
for (int i = 0; i < countriesVisited+1; i++) {
tmp[i] = new char[strlen(country)];
}
for (int i = 0; i < countriesVisited; i++) {
int f = 0;
while (visa[i][f-1] != '\0') {
tmp[i][f] = visa[i][f];
f++;
}
}
for (int i = 0; i <= strlen(country); i++) {
if (i == strlen(country)) {
tmp[countriesVisited][i] = '\0';
break;
}
tmp[countriesVisited][i] = country[i];
}
countriesVisited++;
for (int i = 0; i < countriesVisited-1; i++) {
delete[]visa[i];
}
visa = tmp ;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
tmp [i] = new Char [strlen(country)];
在这里您要分配strlen(country)的内存
但是在此循环中:
在这里,您正在访问不分配的内存,而这不允许,
因此,将条件更改为
i&lt; strlen(country)
tmp[i] = new char[strlen(country)];
here you are allocating memory in amounts of strlen(country)
but in this loop:
here you are accessing to the memory which is not allocated and this not allowed,
so change the condition to
i < strlen(country)