gpt4 book ai didi

c - 从 C 文本文件中提取随机单词时出现段错误

转载 作者:行者123 更新时间:2023-11-30 20:14:05 25 4
gpt4 key购买 nike

我正在编写一个程序,从 C 语言的文本文件中提取 30 个随机单词。但是我遇到了段错误,而且我不明白为什么。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main(int argc, char** argv)
{
char str[100], new_str[100], new_str2[100], new_str3[100];
char* pch;
char* pch1, pch2;
FILE* fp = fopen(argv[1], "r");
int size = 30, str_pos = 0, str_num = 0, c = 0, str_size = 15;
char buf[100];
char arr[30][100];

if(fp == NULL)
{
perror("The following error occured");
exit(-1);
}

for (int i = 0; i < 30; i++)
{
srand(time(NULL)+i);

str_num = rand() % size;


// skip n strings
while (str_num > 0)
{
fgets(buf, 100, fp);
str_num--;
}

srand(time(NULL)+str_num);

str_pos = rand() % str_size;

// get the string
if( fgets(str, 100, fp) != NULL)
{
// move str over n places
pch = str + str_pos;
pch = strchr(pch,' ');
strcpy(new_str, pch); //New SEG FAULT
pch = new_str;
pch1 = strchr(pch+1,' ');
printf("pch1 %s", pch1);

*pch1 = '\0'; //SEG FAULT occurs here

strcpy(new_str2,new_str);
}
else
{
fgets(str,100,fp);
}

strcpy(arr[i],new_str2);

for (int i =0; i < 100; i++)
{
str[i]= 0; new_str[i]=0; new_str2[i]=0; buf[i]=0;
}

pch = 0; pch1 = 0;

rewind(fp);
}

fclose(fp);

for (int i = 0; i < 30; i++)
{
printf("\t%s\n",arr[i]);
}

return 0;
}

我检查了调试器,我收到段错误的行是:

*pch1 = '\0';

知道我做错了什么吗?

编辑:

here is the debug output after adding if(pach1) statementProgram received signal SIGSEGV, Segmentation fault.
0x00007fff906e4172 in strlen () from /usr/lib/system/libsystem_c.dylib
(gdb) where
#0 0x00007fff906e4172 in strlen () from /usr/lib/system/libsystem_c.dylib
#1 0x00007fff906f4564 in stpcpy () from /usr/lib/system/libsystem_c.dylib
#2 0x00007fff90766fb7 in __strcpy_chk ()
from /usr/lib/system/libsystem_c.dylib
#3 0x0000000100000c77 in main (argc=2, argv=0x7fff5fbffcc8)
at randWordSelector.c:52

在 goto 语句的 for 循环顶部添加了这些更改和“tryagain:”,现在一切正常,这是代码

      if (pch)
{
strcpy(new_str, pch);
pch = new_str;
}
else
{
goto tryagain;
}

pch1 = strchr(pch+1,' ');

if (pch1)
{
*pch1 = '\0';
strcpy(new_str2,new_str);
}
else
{
goto tryagain;
}

最佳答案

改变

printf("pch1 %s", pch1);
*pch1 = '\0';

if (pch1) {
printf("pch1 %s", pch1);
*pch1 = '\0';
}

如果在给定字符串中找不到 ' 'strchr 可能会返回 NULL。

编辑:将 strcpy(new_str, pch); 更改为

if (pch)
strcpy(new_str, pch);

关于c - 从 C 文本文件中提取随机单词时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com