【发布时间】:2017-04-27 21:10:26
【问题描述】:
我一直在搞乱动态内存,结果碰上了一堵巨大的墙。
我正在尝试创建一个程序,用户可以在其中输入任意数量的字符串,然后可以随时退出,但是在输入第二个字符串后,程序崩溃而没有给我任何特定的错误消息。
#include "stdafx.h"
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "new"
int _tmain(int argc, _TCHAR* argv[])
{
//Variables
int i=0,end=0,requiresSize=1;
char ** temp;
char item[256]="a";
char ** requires;
//Initialize each element in requiers
requires = new char * [requiresSize];
for(int j=0;j<requiresSize*2;j++){
requires[j]= new char[256];
}
while(strcmp(item,"q-")){
end=0;
printf("Enter h- for help.\nEnter q- to quit.\n");
printf("Please enter a string\n");
gets_s(item);
if(!strcmp(item,"h-")){
printf("Enter a string to add to the list.\nEnter p- to print the list.\n");
end=1;
}
if(!strcmp(item,"q-")){
break;
}
if(!strcmp(item,"p-")){
if(requires[0]!=NULL){
for(int j=0;j<requiresSize;j++){
printf("%d. %s\n",j,requires[j]);
}
}
end=1;
}
while(end==0){
printf("check1:i=%d\n",i);
//if search index is larger than size of the array,reallocate the array
if(i>= requiresSize){
temp = new char * [requiresSize*2];
//Initialize each element in temp
printf("check2:temp initalized\n");
for(int j=0;j<requiresSize*2;j++){
temp[j]= new char[256];
}
printf("check3:temp itmes initialized\n");
for(int j =0;j<requiresSize;j++){
//for each element in requires, copy that element to temp
temp[j]=requires[j];
}
printf("check4:copied requires into temp\n");
delete * requires;
requires = temp;
printf("check5:deleted requires and set requires equal to temp\n");
delete temp;
requiresSize = requiresSize *2;
}
printf("check6:\n");
//if the index at requires is not empty, check to see if it is the same as given item
if(requires[i]!= NULL){
printf("check8:index at requires is not empty\n");
//I know the error occurs here, something to do with accessing requires[i]
if(!strcmp( item, requires[i])){
printf("check9:index at requires is the same as item\n");
//if they are the same, break out of the loop, item is already included
break;
}else{
printf("check10:index at requires is different\n");
//otherwise, increase the index and check again (continue loop)
i++;
break;
}
}else{
printf("check11:index at requires is null, item added\n");
//if the index is empty, add the item to the list and break out of loop
requires[i]= item;
break;
}
printf("check7\n");
}
}
delete requires;
return 0;
}
提前谢谢你。
【问题讨论】:
-
使用 std::string - 您的代码基本上是 C 语言,带有新的替换 malloc。
-
顺便说一句,您的第一个
for循环已经访问了您分配的数组超出其边界并调用 未定义的行为 -
#include "stdafx.h"的存在表明您正在使用 Visual Studio。 Visual Studio 拥有市场上最好的调试器之一,即使不是最好的。我建议利用它来单步执行代码,并留意程序开始偏离预期的位置。 -
我正在尝试创建一个程序,用户可以在其中输入任意数量的字符串 --
std::vector<std::string>。你写的所有代码都被那个替换了。 -
Example。将其与您正在尝试做的事情进行比较。