c - strstr() 导致段错误

标签 c

这里的目标是将整个文本文件转储到缓冲区中,然后使用 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/

相关文章:

c - 如何计算 .txt 文件中有多少个单词?在 C

C - if else 的三元运算符

c 中结构的冲突类型

c - Posix 线程消费者无法正确打印

c - 使用 printf 使输出与输入一样精确?

c - 递增函数指针

c - 将带有 float 的txt文件读入二维矩阵

c - 如何解析/proc/meminfo

代码没有正确输出

c++ - C/C++ 中的 C 风格无符号字符解析和操作 - 段错误