strcpy segfault 将文件内容复制到数组

发布于 2025-01-11 09:02:49 字数 776 浏览 0 评论 0原文

这是我的代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

も让我眼熟你 2025-01-18 09:02:49

如果该数组是在文件作用域中声明的,则您有一个未初始化指针或空指针的数组,

char *urls[MAX_WORD + 1];

因此此调用

strcpy(urls[index], url);

会调用未定义的行为。

看来您需要的是声明一个二维数组,例如

char urls[MAX_WORD + 1][MAX_WORD + 1];

或者在原始数组中为存储的字符串动态分配内存。像这样的东西

urls[index] = malloc( strlen( url ) + 1 );
if ( urls[index] != NULL ) strcpy(urls[index], url);
else /* some error processing */;

You have an array of uninitialized pointers or null pointers if the array is declared in the file scope

char *urls[MAX_WORD + 1];

So this call

strcpy(urls[index], url);

invokes undefined behavior.

It seems what you need is to declare a two-dimensional array like for example

char urls[MAX_WORD + 1][MAX_WORD + 1];

Or in the original array allocate dynamically memory for the stored string. Something like

urls[index] = malloc( strlen( url ) + 1 );
if ( urls[index] != NULL ) strcpy(urls[index], url);
else /* some error processing */;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文