Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Upon creation of 3 – 5 nodes, segmentation fault is encountered. Why?

I am currently trying to create a phonebook with a linked list. I am focusing first on the insertion function but the problem is that once I create 3 – 5 nodes, onlineGDB shows the error "malloc : corrupted top size", and VS Code shows that I got a segmentation error.

I assume this is an error with the way I am allocating memory. This is the first time that I am working on a structure that contains strings as data instead of integer so I might have missed a thing or two.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node{
    char name[30];
    char number[15];
    struct node *next;
};

void showMenu();
void insertData(struct node **head, char person[], char phone[]);
void showData(struct node *head);

int main(){

    struct node *head = NULL;
    char name[30], number[15];
    while(1)
    {
        printf("Name : ");
        scanf(" %[^\n]s", name);
        printf("Number: ");
        scanf(" %[^\n]s", number);
        insertData(&head, name, number);
        showData(head);
    }
    return 0;
}

void insertData(struct node **head, char person[], char phone[]){

    struct node *new_node = (struct node*) malloc(sizeof(struct node*));
    strcpy(new_node->name, person);
    strcpy(new_node->number, phone);
    new_node->next = *head;
    *head = new_node;
}

void showData(struct node *head){

    while(head != NULL)
    {
        printf("%s\t\t%s\n", head->name, head-> number);
        head = head->next;
    }    
    printf("\n");
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use malloc(sizeof(struct node)) instead of malloc(sizeof(struct node*)) in your function insertData(). You want to allocate the size of the node and not the pointer to node.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading