gpt4 book ai didi

c - 使用 valgrind 和 gdb 进行调试

转载 作者:行者123 更新时间:2023-11-30 15:11:04 27 4
gpt4 key购买 nike

下午好!这是我在这里发表的第一篇文章!

当我使用 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;
}

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

最佳答案

您正在初始化tzl[2]带有指向 4 字节 block 的指针:

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

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

tzl[MAX_INDEX] -> suiv = NULL;

声明z_mstruct block *并更改malloc(1<<MAX_INDEX)malloc(sizeof(struct block))首先。

您还应该检查以确保 malloc没有返回 NULL,您可能应该避免强制转换 malloc的返回值。

关于c - 使用 valgrind 和 gdb 进行调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35826426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com