Reputation: 39
The malloc part crashes in the following code, but only in VS and not in CodeBlocks. As I have learned, that means that I am probably triggering some undefined behavior. But I can't figure out why...
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#define TableLength 29
typedef int info;
typedef int tipkey;
typedef struct element
{
tipkey key;
info info;
} element;
typedef struct node* nodepointer;
typedef struct node
{
element element;
nodepointer next;
} tipnod;
typedef nodepointer table[TableLength];
int main()
{
table table;
for (int i = 0; i < TableLength; i++)
{
table[i] = NULL;
}
for (int i = 0; i < TableLength; i++)
{
element el = { i, i };
table[i] = (nodepointer)malloc(sizeof(nodepointer));
table[i]->element = el;
table[i]->next = NULL;
}
getch();
return 0;
}
}```
Upvotes: 0
Views: 81
Reputation: 154335
Avoid allocation size mistakes.
Allocate to the size of the refenced object and drop the unneeded cast.
ptr = malloc(sizeof *ptr);
It is that simple.
In OP's case
//table[i] = (nodepointer)malloc(sizeof(nodepointer));
table[i] = malloc(sizeof (*table[i]));
// or
table[i] = malloc(sizeof *table[i]);
// or
table[i] = malloc(sizeof table[i][0]);
Upvotes: 0
Reputation: 302
Tested on VSCode: Extending @dbush response, you allocating less memory than required and trying to access unallocated memory. you can refer this What happens if I use malloc with the wrong size?
Tested on your code:
printf("size of nodepointer: %lu\n", sizeof(nodepointer));
printf("size of node: %lu\n", sizeof(struct node));
Output:
size of nodepointer: 8
size of node: 16
Upvotes: 1
Reputation: 224387
You're not allocating enough memory:
table[i] = (nodepointer)malloc(sizeof(nodepointer));
You're allocating space for a nodepointer
instead of a tipnod
(?) a.k.a struct node
. As a result, you're writing past the end of allocated memory when you write to the struct, triggering undefined behavior.
You want to use that for the size instead.
table[i] = malloc(sizeof(tipnod));
Note also that you shouldn't cast the return value of malloc
as that can hide other errors in your code.
Upvotes: 2