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

Error when accessing allocated memory in c

If understand my own code correctly I am allocating space for 3 pointers pointing to a data type ListNode and then looping three times and adding a number to each node.
I know that the nodes are not connected to one another

now when I try to access any node from the allocated space I get the error commented in the bottom of the code

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


typedef struct ListNode {
    int val;
    struct ListNode *next;
    } ListNode;

int main(void)
{    
    int nums[] = {2,3,4};

    ListNode * ptr = (ListNode*)malloc(3*sizeof(ListNode*));
    
    for (int i=0; i < sizeof(nums)/sizeof(nums[0]); i++ )
    {
        ListNode new;
        new.val = nums[i];
        ptr[i] = new;
    }

    printf("%d \n",ptr[0].val);

    free(ptr);
    return 0; 
}
/*
Error: 
malloc(): corrupted top size
Aborted (core dumped)
*/

why do I get this error and how to properly access each node in the allocated space

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 :

You’re not allocating enough space:

ListNode * ptr = (ListNode*)malloc(3*sizeof(ListNode*));

Here you’re attempting to dynamically allocate a 3 element of array of ListNode structs, but you’re instead allocating space for 3 pointers to ListNode. These pointers are smaller that the structs, so you end up writing past the end of allocated memory, triggering undefined behavior and a crash.

You want to allocate space for 3 structs, not 3 pointers:

ListNode * ptr = (ListNode*)malloc(3*sizeof(ListNode));

Or better yet:

ListNode * ptr = (ListNode*)malloc(3 * sizeof *ptr);

As this doesn’t depend on what the type of ptr is.

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