[英]An error when dynamically allocating memory for a char*
So the main problem is there is run time error in the code: 因此,主要问题是代码中存在运行时错误:
char *wordBank[]= {new char[numWords+1]};
char buffer1[41];
for(int i=0; i<numWords;i++){
ifile >> buffer1;
int len = strlen(buffer1);
cout << buffer1<<"and"<<len <<endl;
wordBank[i] = new char[len + 1];
strncpy(wordBank[i], buffer1,len);
cout << wordBank[i]<<"and"<<len <<endl;
}
is it starts to mess up with what is in wordBank. 它开始弄乱wordBank中的内容了吗? It gets the words from a txt file into buffer1 and then copy if into the dynamically allocated char* array of wordBank.
它将单词从txt文件获取到buffer1,然后将其复制到wordBank的动态分配的char *数组中。 However I always get segmentation fault and the words are all incorrect.
但是,我总是会遇到细分错误,并且所有单词都不正确。 What did I do wrong?
我做错了什么?
You can simplify the code using C++ instead of C: 您可以使用C ++而不是C简化代码:
vector<string> wordBank(numWords);
string buffer1;
for (int i = 0; i < numWords; i++) {
ifile >> buffer1;
size_t len = buffer1.length();
cout << buffer1 << "and" << len << endl;
wordBank[i] = buffer1;
cout << wordBank[i] << "and" << len << endl;
}
Or even simpler, but adding error checking: 甚至更简单,但添加了错误检查:
vector<string> wordBank(numWords);
for (int i = 0; i < numWords; i++) {
if (ifile >> wordBank[i])
cout << wordBank[i] << "and" << len << endl;
else { // no more words
wordBank.resize(i); // chop off the unused portion
break;
}
}
This line is wrong: 这行是错误的:
char *wordBank[] = {new char[numWords+1]};
wordBank
is an array with one element, the value of that one element is a pointer to a character array with numWords+1
characters. wordBank
是一个包含一个元素的数组,该元素的值是一个指向具有numWords+1
字符的字符数组的指针。 When you access wordBank[1]
you're outside the bounds of the array, which results in undefined behavior. 当您访问
wordBank[1]
您将超出数组的范围,这将导致未定义的行为。
What you apparently want is: 您显然想要的是:
char **wordBank = new char*[numWords];
This creates a dynamically-allocated array of numWords
char*
elements, which you will then assign in the for
loop. 这将创建一个由
numWords
char*
元素动态分配的数组,然后将其分配给for
循环。
I don't see any need for numWords+1
. 我看不到需要
numWords+1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.