【发布时间】:2020-08-02 03:08:01
【问题描述】:
我也收到了来自 Valgrind 的这条消息。
valgrind: m_mallocfree.c:280 (mk_plain_bszB): Assertion 'bszB != 0' failed.
valgrind: This is probably caused by your program erroneously writing past the
end of a heap block and corrupting heap metadata. If you fix any
invalid writes reported by Memcheck, this assertion failure will
probably go away. Please try that before reporting this as a bug.
如果有人可以测试,这是我的代码
#include <stdio.h>
#include <stdlib.h>
//creating the node structure
typedef struct node
{
char first_name[45];
struct node *next_node;
}
node;
int main(void)
{
// creating the pointer list and setting it to NULL;
node *list = NULL;
char name[20];
// creating the first node
node *n = malloc(sizeof(n));
if(n == NULL)
{
printf("malloc cound't get enough mem.\n");
return 1;
}
// dereferencing the name in node and the next_node pointer in n
printf("Please print the users first name\n");
// getting user input and storing it in first name
scanf("%s",n->first_name);
n->next_node = NULL;
// having list point at n the first node
list = n;
// creating the tempory pointer we will use to make the linked list in a loop
node *temp = NULL;
// generating a singly linked list with a loop
for(int i = 0; i < 7; i++)
{
temp = n;
n = malloc(sizeof(node));
if(n == NULL)
{
printf("malloc wasn't able to allocate the memory we needed. Aborting the program\n");
return 1;
}
//dereferencing the new n node
printf("Please print the users first name\n");
// getting user input on the name and storing it in the first name array
scanf("%s",n->first_name);
n->next_node = temp;
list = n;
}
// looping through the linked list and printing out the values
for(node*tmp = list; tmp!=NULL;tmp=tmp->next_node)
{
printf("The name of the user is %s\n",tmp->first_name);
}
// freeing the linked list
while(list!=NULL)
{
node *tempr = list->next_node;
free(list);
list = tempr;
}
}
我不知道如何解决这个错误。如果有人可以提供帮助,我将不胜感激。
【问题讨论】:
-
使用调试信息构建您的程序。这是 GCC 或 Clang 的
-g标志。然后 Valgrind 会告诉你你的 bug 到底在哪里。 -
OT:关于:
printf("malloc cound't get enough mem.\n");错误消息应该输出到stderr,而不是stdout。当错误来自 C 库函数时,还应输出系统认为发生错误的文本原因。建议:perror("malloc could't get enough mem.");作为函数:perror()用于处理这两个活动