gpt4 book ai didi

c - 如何将 malloc 分配给另一个结构内部的结构?

转载 作者:行者123 更新时间:2023-11-30 19:32:07 24 4
gpt4 key购买 nike

在第一个 .h 文件中,我有这个结构:

typedef struct system
{
char* name;
DArray Info;
} *System;

.c 文件中我有这个函数:

System createSystem(char *name){
if (!name){
return NULL;
}
System newSystem=malloc(sizeof(*newSystem));
if (!newSystem){
return NULL;
}
newSystem->name=malloc(sizeof(strlen(name)+1));
if (!newSystem->name){
free(newSystem);
return NULL;
}
strcpy(newSystem->name,name);
newSystem->Info=malloc(sizeof *(newSystem->Info));
if (!newSystem->Info){
free(newSystem->name);
free(newSystem);
return NULL;
}
newSystem->Info->x=0;
newSystem->Info->elements=NULL;
return newSystem;
}

在另一个 .h 文件中,我有 struct dArray:

typedef struct dArray
{
int x;
Element *elements;
} *DArray;

其中 Element 可以是任何类型。

但是,该函数在 Eclipse 中总是停止工作,并且出现错误

hw stopped working

我知道问题出在这一行:

 newSystem->Info=malloc(sizeof(*newSystem->Info));

但我不明白为什么这是一个问题,因为我试图以常规方式 malloc 到 struct DArray!

我一直在主文件中使用这个测试:

int main() {
sys=createSystem("ss1");
if (sys) {
printf ("ok");
return 0;
}

如有任何帮助,我们将不胜感激。

最佳答案

System createSystem(char *name){
if (!name){
return NULL;
}
System newSystem=malloc(sizeof *newSystem);
if (!newSystem){
return NULL;
}
newSystem->name=malloc(sizeof *newSystem->name * (strlen(name)+1)); // <-- change here.
if (!newSystem->name){
free(newSystem);
return NULL;
}
strcpy(newSystem->name,name);
newSystem->Info=malloc(sizeof *newSystem->Info);
if (!newSystem->Info){
free(newSystem->name);
free(newSystem);
return NULL;
}
newSystem->Info->x=0;
newSystem->Info->elements=NULL;
return newSystem;
}

如果您将字符串复制到动态分配的内存,它(malloc)基本上会分配sizeof (strlen(str)+1)字节的内存。这只不过是应用于 size_tsizeof 运算符,它不太可能容纳字符串。 (我的机器上有 5 个字符)。(为什么size_t?因为函数strlen有一个签名size_t strlen(const char *s);)

另外,在我的系统中,sizeof size_t 是 4 个字节。所以基本上你分配了 5 个字节。这意味着该字符串将由 5 个字符组成,包括 nul 终止字符。

任何超过 length 的内容都会像 "ABCDED" 一样,您正在从分配的内存中写入,从而导致非法内存访问 - 这具有未定义的行为。在你的情况下,它只是停止。

为了添加更多说明,在您的情况下,我猜当您输入字符串时,您传递的长度超过了4。但如果您传递字符串“ss1”,那么这将起作用。

newSystem->name=malloc(sizeof *newSystem->name * (strlen(name)+1)); 可以更清楚地写成 newSystem->name=malloc( strlen(名称)+1);.由于 sizeof char1 字节,我们避免了它。

您稍后可以尝试查找strdup不属于 ISO 标准的功能。

关于c - 如何将 malloc 分配给另一个结构内部的结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47477317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com