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
CodePudding user response:
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.
CodePudding user response:
int nums[] = {2,3,4};
size_t k = sizeof(nums)/sizeof(nums[0]);
ListNode * ptr = malloc(k*sizeof(ListNode));
Do not cast the malloc's result for reasons you can find in many places, including on SO.
Allocate
COUNT
timessizeof(object)
, notsizeof(object*)
bytes.