Я получаю сообщение об ошибке неверной записи размера 8 в моем коде при запуске Valgrind - PullRequest
0 голосов
/ 19 апреля 2020

Я также получаю это сообщение от 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;
    }

}

Я заблудился, как исправить эту ошибку. Если бы кто-нибудь мог помочь, я был бы признателен.

1 Ответ

2 голосов
/ 19 апреля 2020
node *n = malloc(sizeof(n));

вы резервируете пространство с размером указателя в качестве аргумента (точно не то, что вам нужно), чтобы зарезервировать пространство с размером самого struct, используйте:

node *n = malloc(sizeof(*n));

или

node *n = malloc(sizeof(node));

, как вы делаете в for l oop.

...