Valgrind ==10731== 大小为 8 的无效写入

Valgrind ==10731== invalid write of size 8

这是我的代码:

struct FileNode {
    char *filename;
    double tf;
    struct FileNode *next;
};

typedef struct FileNode *FileList;

FileList newFileList(){
    FileList fl = malloc(sizeof(FileList));
    fl->next = NULL;
    fl->tf = 0.0;

    return fl;
}

这是我的 valgrind 输出。

==10731== Invalid write of size 8
==10731==    at 0x1097B7: newFileList (invertedIndex.c:73)
==10731==    by 0x109852: generateInvertedIndex (invertedIndex.c:89)
==10731==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==10731==    by 0x109244: main (testInvertedIndex.c:23)
==10731==  Address 0x4bd10a0 is 8 bytes after a block of size 8 alloc'd
==10731==    at 0x483577F: malloc (vg_replace_malloc.c:299)
==10731==    by 0x1097AE: newFileList (invertedIndex.c:72)
==10731==    by 0x109852: generateInvertedIndex (invertedIndex.c:89)
==10731==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==10731==    by 0x109244: main (testInvertedIndex.c:23)
==10731== 
==10731== Invalid write of size 8
==10731==    at 0x1097C7: newFileList (invertedIndex.c:74)
==10731==    by 0x109852: generateInvertedIndex (invertedIndex.c:89)
==10731==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==10731==    by 0x109244: main (testInvertedIndex.c:23)
==10731==  Address 0x4bd1098 is 0 bytes after a block of size 8 alloc'd
==10731==    at 0x483577F: malloc (vg_replace_malloc.c:299)
==10731==    by 0x1097AE: newFileList (invertedIndex.c:72)
==10731==    by 0x109852: generateInvertedIndex (invertedIndex.c:89)
==10731==    by 0x1092B4: test1 (testInvertedIndex.c:36)
==10731==    by 0x109244: main (testInvertedIndex.c:23)

我不知道为什么会这样。我输入了一个 double,它说大小 8 的写入无效。 与 fl->next = NULL

相同
  1. 使用:
FileList fl = malloc(sizeof(struct FileNode));

因为 sizeof(FileList) 只分配 8 bytes 并且您正在尝试写入超过 8 个字节。另一方面,sizeof(struct FileNode)struct FileNode 的所有成员分配 space,这是您的意图,以便稍后您可以存储所需的值。

通过简单的调试打印(或使用调试器),您可以找出大小差异。

  1. fNodePtr_t 可能是一个恰当的名称,而不是 FileList
typedef struct FileNode* fNodePtr_t;
  1. 检查 malloc() 调用的 return 值更安全:
fNodePtr_t newFileList(){
    fNodePtr_t fl = malloc(sizeof(struct FileNode));
    if (NULL == fl) {
        perror ("newFileList");
        return NULL;
    }
    fl->next = NULL;
    fl->tf = 0.0;

    return fl;
}