代码之家  ›  专栏  ›  技术社区  ›  trueCamelType

为什么在修改指向结构的指针后出现分段错误?

  •  -1
  • trueCamelType  · 技术社区  · 5 年前

    我现在有函数代码,当我试图从文件到数组的转换中生成函数时,我得到了一个分割错误。我知道里面的东西 fileToArray 是正确的(只要 myData 因为在函数内部, myData.length myData.array 全部正确返回。但是,在主指针被引用之后,我得到一个seg错误。我是C新手,但所有这些都是在没有指向结构的特定指针的情况下工作的。

    所以,如果我用一个带有多行文本的文件的参数调用这个程序,就会发生set错误。

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <fcntl.h>
    #include <sys/stat.h>
    #include <string.h>
    #include <unistd.h>
    
    typedef struct {
        int length;
        char** array;
    } FileStruct;
    
    void fileToArray(FileStruct* fileDataPtr, int argc, char *argv[]){
        int  fd, i, n, count;
        struct stat statbuf;
        char *buf, *inbuf, *str, *saveptr;
        char **array;
    
        if ((fd = open(argv[1], O_RDONLY)) == -1) {
            printf("Error opening file %s\n", argv[1]);
            exit (-1);
        }
    
        if (lstat(argv[1], &statbuf) < 0) {
            printf("Unable to lstat file %s\n", argv[1]);
            exit (-1);
        }
        off_t filesize = statbuf.st_size;
        buf = malloc(sizeof(char)*filesize);
        array = malloc(sizeof(char *)*filesize);
    
        count = 0;
        if ((n = read(fd, buf, filesize)) > 0){
            inbuf = buf;
            for (i = 1; ; inbuf = NULL, i++) {
                str = strtok_r(inbuf, "\n", &saveptr); 
                if (str == NULL)
                   break;
                array[count] = malloc(sizeof(char)*(strlen(str)+1));
                strcpy(array[count++], str);
            }
        } else {
            printf("Error reading input file\n");
            exit (-1);
        }
    
        close(fd);
    
        // I know array works because it prints correctly here.
        for (i = 0; i < count; i++) {
        printf("%s\n", array[i]);
        free(array[i]);
        }
    
        fileDataPtr->length = count;
        fileDataPtr->array = array;
    
        free(array);
        free(buf);
    }
    
    int main(int argc, char *argv[]) {
        int i;
    
        FileStruct myData;
        FileStruct* fileDataPtr = &myData;
        fileToArray(fileDataPtr, argc, argv);
    
        printf("length: %i", myData.length);
    
        // I know this doesn't work because anything related to myData causes Seg fault.
        // for (i = 0; i < 1; i++) {
        //     printf("%s\n", myData.array[i]);
        //     free(myData.array[i]);
        // }
    
        return 0;
    }
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   1201ProgramAlarm    5 年前

    接近尾声 fileToArray ,你指派 array fileDataPtr->array ,然后在下一行你就可以自由了 数组 . 这将离开 文件数据ptr->数组 指向释放的内存(悬挂的指针)。当您稍后取消引用它时,您将进入未定义的行为,任何事情都可能发生。

    由于分配将已分配内存的所有权转移到 fileDataPtr ,您不需要释放 数组 回来之前 文件数组 .

    移除 free(array); 线。