gpt4 book ai didi

c - strstr() 导致段错误

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

这里的目标是将整个文本文件转储到缓冲区中,然后使用 strcasestr() 函数查找我在缓冲区中查找的单词的指针。它不断地给我段错误错误。起初,我认为可能是尺寸问题,所以我尝试使用较小的尺寸,但也不起作用。该函数仅适用于我在实际代码中创建的字符串(例如:char * bob = "bob"; char * bobsentence = "bob is Cool"; strstr(bobsentence, bob);)。这让我相信它与 fgets() 有关。感谢任何帮助,我真的很坚持这个。

  #define _GNU_SOURCE //to use strcasestr 

#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void textEdit(char *path, char *word){

printf("%s\n", path);


FILE *textFile;
//FILE *locationFile;
//FILE *tempFile;

char counter[1024];
int count = 0;

textFile = fopen(path, "r+");
//locationFile = fopen(path, "r+");
//opens file to read and write and opens temp file to write

if( textFile == NULL){ //|| tempFile == NULL || locationFile == NULL) ) {
printf ("\nerror\n");
return;
}

// SECTION : ALLOCATES MEMORY NEEDED FOR COPY TEXT IN ARRAY
// finds number of lines to estimate total size of array needed for buffer
while((fgets(counter, sizeof(counter), textFile)) != NULL){
count++;
}

fclose(textFile);
FILE *tempFile = fopen(path, "r+");

count *= 1024;
printf("%d %zu\n",count, sizeof(char));
char *buffer = malloc(count); //1024 is the max number of characters per line in a traditional txt

if(buffer == NULL){ //error with malloc
return;
}


// SECTION : DUMPS TEXT INTO ARRAY

if(fgets(buffer, count, tempFile) == NULL){
printf("error");
} //dumps all text into array

printf("%s\n", buffer);

char * searchedWord;

while((searchedWord = strcasestr(buffer, word)) != NULL){


}

fclose(tempFile);
//fclose(locationFile);

free(buffer);
}

最佳答案

看来您忘记将 count 变量初始化为 0:

int count = 0;

您递增它,它可以包含任何随机值,甚至是负值。

另外,请注意,您对 strstr 的使用看起来不正确。该函数返回指向第一个匹配项的指针。请注意,它不记得已经找到的匹配项,因此如果存在匹配项,它应该在此循环中永远循环。相反,它应该看起来像:

char *pos = buffer;
while((pos = strcasestr(pos, word)) != NULL){
searchedWord = pos;
/* do something with searchedWord but remember that it belongs to
allocated buffer and can't be used after free() */
pos++;
}

关于c - strstr() 导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48650970/

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