Home > Mobile >  Valgrind ==10731== invalid write of size 8
Valgrind ==10731== invalid write of size 8

Time:03-03

Here is my code:

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

Here is my valgrind output.

==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)

I don't know why it is causing this. I am putting in a double and it says invalid write of size 8. The same with fl->next = NULL

CodePudding user response:

  1. Use :
FileList fl = malloc(sizeof(struct FileNode));

Because sizeof(FileList) only allocates 8 bytes & you're trying write beyond 8 bytes. On the other hand sizeof(struct FileNode) allocates space for all the members of struct FileNode which is your intention, so that later you can store desired values.

With a simple debug print (or using a debugger), you can find out the size differences.

  1. fNodePtr_t may be an apt name instead of FileList.
typedef struct FileNode* fNodePtr_t;
  1. It's safer to check the return value of malloc() call:
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;
}
  • Related