strstr()导致分段错误错误

时间:2018-02-06 19:58:16

标签: 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);    
}    

1 个答案:

答案 0 :(得分:2)

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

int count = 0;

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

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

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++;
}