使用 valgrind 和 gdb 进行调试

Debugging with valgrind and gdb

下午好!这是我第一次 post 来这里!

我在用valgrind的时候出现了一个无效的写入错误,但是当我用gdb的时候我可以解决这个问题!

 #include <stdio.h>
 #include <stdlib.h>
 #define MAX_INDEX 2

 void *z_m = 0;
 struct block {
    struct block * suiv;
 };

 //Declaration of a global array 
 struct block * tzl[MAX_INDEX+1];

 //Function used to dislay tzl in the main.
 void display() {
    for(int i=0; i<=MAX_INDEX; i++) {
        struct bloc * tmp = tzl[i];
        printf("%d  =>  ",i);
        while (tmp!=NULL) {
            printf(" %li  ->",(unsigned long)tmp);
            tmp = tmp -> suiv;
        }
        printf("\n");
    }
 }

 int main() {
    z_m = (void *) malloc(1<<MAX_INDEX);
    for (int i=0; i<MAX_INDEX; i++) 
    {
         tzl[i] = NULL;
    }
    tzl[MAX_INDEX] = z_m;
    //Here is the problem with valgrind
    tzl[MAX_INDEX] -> suiv = NULL;
    display();
    free(z_m);
    return 0;
}

可能是什么问题?谢谢你的回答。

您正在使用指向 4 字节块的指针初始化 tzl[2]

tzl[MAX_INDEX] = z_m;    /* z_m is malloc(4) */

但是您随后将其视为指向 struct block:

的指针
tzl[MAX_INDEX] -> suiv = NULL;

首先将 z_m 声明为 struct block * 并将 malloc(1<<MAX_INDEX) 更改为 malloc(sizeof(struct block))

您还应该检查以确保 malloc 没有 return NULL,并且您应该避免强制转换 malloc 的 return 值。