为什么指针数组的动态分配会崩溃?
Why dynamic allocation of array of pointers crashes?
malloc 部分在以下代码中崩溃,但仅在 VS 中崩溃,在 CodeBlocks 中不崩溃。据我所知,这意味着我可能触发了一些未定义的行为。但是我想不通为什么...
#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;
}
}```
您没有分配足够的内存:
table[i] = (nodepointer)malloc(sizeof(nodepointer));
您正在为 nodepointer
而不是 tipnod
(?) a.k.a struct node
分配 space。因此,当您写入结构时,您正在写入已分配内存的末尾,从而触发未定义的行为。
您想改用那个尺寸。
table[i] = malloc(sizeof(tipnod));
另请注意,您不应强制转换 malloc
的 return 值,因为这会隐藏代码中的其他错误。
在 VSCode 上测试:
扩展 @dbush 响应,您分配的内存少于所需的内存并尝试访问未分配的内存。你可以参考这个What happens if I use malloc with the wrong size?
在您的代码上测试:
printf("size of nodepointer: %lu\n", sizeof(nodepointer));
printf("size of node: %lu\n", sizeof(struct node));
输出:
size of nodepointer: 8
size of node: 16
避免分配大小错误。
分配给引用对象的大小并删除不需要的转换。
ptr = malloc(sizeof *ptr);
就这么简单
OP 的情况
//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]);
malloc 部分在以下代码中崩溃,但仅在 VS 中崩溃,在 CodeBlocks 中不崩溃。据我所知,这意味着我可能触发了一些未定义的行为。但是我想不通为什么...
#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;
}
}```
您没有分配足够的内存:
table[i] = (nodepointer)malloc(sizeof(nodepointer));
您正在为 nodepointer
而不是 tipnod
(?) a.k.a struct node
分配 space。因此,当您写入结构时,您正在写入已分配内存的末尾,从而触发未定义的行为。
您想改用那个尺寸。
table[i] = malloc(sizeof(tipnod));
另请注意,您不应强制转换 malloc
的 return 值,因为这会隐藏代码中的其他错误。
在 VSCode 上测试: 扩展 @dbush 响应,您分配的内存少于所需的内存并尝试访问未分配的内存。你可以参考这个What happens if I use malloc with the wrong size?
在您的代码上测试:
printf("size of nodepointer: %lu\n", sizeof(nodepointer));
printf("size of node: %lu\n", sizeof(struct node));
输出:
size of nodepointer: 8
size of node: 16
避免分配大小错误。
分配给引用对象的大小并删除不需要的转换。
ptr = malloc(sizeof *ptr);
就这么简单
OP 的情况
//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]);