简体   繁体   中英

Debugging with valgrind and gdb

Good afternoon! This is my first post here!

I have an invalid write error when I use valgrind, but when I can figure it when I use 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;
}

What can be the problem? Thank you for answering.

You are initializing tzl[2] with a pointer to a block of 4 bytes:

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

But you are then treating it as a pointer to struct block :

tzl[MAX_INDEX] -> suiv = NULL;

Declare z_m as struct block * and change malloc(1<<MAX_INDEX) to malloc(sizeof(struct block)) for a start.

You should also check to make sure malloc did not return NULL, and you should probably refrain from casting malloc 's return value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM