gpt4 book ai didi

c - strcat() 仅在程序完成后才导致段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:52 25 4
gpt4 key购买 nike

这是一个总结文本的程序。到目前为止,我正在计算文本中每个单词的出现次数。但是,我在 strcat 中遇到了段错误。

Program received signal SIGSEGV, Segmentation fault.
0x75985629 in strcat () from C:\WINDOWS\SysWOW64\msvcrt.dll

但是,在单步执行代码时,程序会按预期运行 strcat() 函数。直到第 75 行程序结束时,我才收到错误。

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

#define MAXTEXT 1000
#define MAXLINE 200
#define MAXWORDS 200
#define MAXWORD 32

char *strtolower(char *d, const char *s, size_t len);

/* summarizer: summarizes text */
int main(int argc, char *argv[]) {
/* argument check */
char *prog = argv[0];
if (argc < 1) {
fprintf(stderr, "%s: missing arguments, expected 1", prog);
exit(1);
}
/* attempt to open file */
FILE *fp;
if (!(fp = fopen(argv[1], "r"))) {
fprintf(stderr, "%s: Couldn't open file %s", prog, argv[1]);
exit(2);
}
/* read file line by line */
char line[MAXLINE], text[MAXTEXT];
while ((fgets(line, MAXTEXT, fp))) {
strncat(text, line, MAXLINE);
}
/* separate into words and count occurrences */
struct wordcount {
char *word;
int count;
};
struct wordcount words[MAXWORDS];
char *token, *delim = " \t\n.,!?";
char word[MAXWORD], textcpy[strlen(text)+1]; /*len of text and \0 */
int i, j, is_unique_word = 1;
strcpy(textcpy, text);
token = strtok(textcpy, delim);
for (i = 0; i < MAXWORDS && token; i++) {
strtolower(word, token, strlen(token));
token = strtok(NULL, delim);
/* check if word exists */
for (j = 0; words[j].word && j < MAXWORDS; j++) {
if (!strcmp(word, words[j].word)) {
is_unique_word = 0;
words[j].count++;
}
}
/* add to word list of unique */
if (is_unique_word) {
strcpy(words[i].word, word);
words[i].count++;
}
is_unique_word = 1;
}

return 0;
}

/* strtolower: copy str s to dest d, returns pointer of d */
char *strtolower(char *d, const char *s, size_t len) {
int i;

for (i = 0; i < len; i++) {
d[i] = tolower(*(s+i));
}

return d;
}

最佳答案

问题出在循环中:while ((fgets(line, MAXTEXT, fp))) strncat(text, line, MAXLINE);。由于多种原因,它是不正确的:

  • text 未初始化,将字符串连接到它具有未定义的行为。未定义的行为确实可能会在函数结束后 导致崩溃,例如,如果返回地址被覆盖。
  • 没有理由使用长度为MAXLINEstrncat()fgets()读取的字符串最多有MAXLINE-1 字节。
  • 您没有检查 text 末尾是否有足够的空间来连接 line 的内容。 strncat(dest, src, n)src 复制最多 n 个字节到 的末尾dest 并始终设置空终止符。它不是strcat()安全 版本。如果该行不适合 text 的末尾,您会出现意外行为,并且您会再次观察到函数结束后 发生崩溃,例如,如果 return地址被覆盖。

您可以尝试使用 fread 读取整个文件:

/* read the file into the text array */
char text[MAXTEXT];
size_t text_len = fread(text, 1, sizeof(text) - 1, fp);
text[text_len] = '\0';

如果 text_len == sizeof(text) - 1,文件对于 text 数组来说可能太大,while 循环会导致缓冲区溢出。

关于c - strcat() 仅在程序完成后才导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45864870/

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