strcpy segfault 将文件内容复制到数组
这是我的代码
char url[MAX_WORD + 1];
char *urls[MAX_WORD + 1];
//char word[MAX_WORD + 1];
while(fscanf(fp, "%100s", url) == 1) {
strcpy(urls[index], url);
index++;
}
这是我在 valgrind 上遇到的错误:
==43177== Process terminating with default action of signal 11 (SIGSEGV) ==43177== Access not within mapped region at address 0x4844000 ==43177== at 0x4838DC8: strcpy (vg_replace_strmem.c:512) ==43177== by 0x109898: generateInvertedIndex (invertedIndex.c:102) ==43177== by 0x1092B4: test1 (testInvertedIndex.c:36) ==43177== by 0x109244: main (testInvertedIndex.c:23)
这是它从中复制的文件的内容
nasa.txt news1.txt file11.txt mixed.txt planets.txt file21.txt info31.txt
我不知道如何收到此错误。我只想将文件的内容复制到 URL 数组中。但这不起作用。
This is my code
char url[MAX_WORD + 1];
char *urls[MAX_WORD + 1];
//char word[MAX_WORD + 1];
while(fscanf(fp, "%100s", url) == 1) {
strcpy(urls[index], url);
index++;
}
This is the error I'm getting on valgrind:
==43177== Process terminating with default action of signal 11 (SIGSEGV) ==43177== Access not within mapped region at address 0x4844000 ==43177== at 0x4838DC8: strcpy (vg_replace_strmem.c:512) ==43177== by 0x109898: generateInvertedIndex (invertedIndex.c:102) ==43177== by 0x1092B4: test1 (testInvertedIndex.c:36) ==43177== by 0x109244: main (testInvertedIndex.c:23)
This is the content of the file it is copying from
nasa.txt news1.txt file11.txt mixed.txt planets.txt file21.txt info31.txt
I don't know how I am getting this error. I just want to copy the content of the file to an array of Urls. But it doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果该数组是在文件作用域中声明的,则您有一个未初始化指针或空指针的数组,
因此此调用
会调用未定义的行为。
看来您需要的是声明一个二维数组,例如
或者在原始数组中为存储的字符串动态分配内存。像这样的东西
You have an array of uninitialized pointers or null pointers if the array is declared in the file scope
So this call
invokes undefined behavior.
It seems what you need is to declare a two-dimensional array like for example
Or in the original array allocate dynamically memory for the stored string. Something like