gpt4 book ai didi

c - 段错误,malloc 字符指针

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:10 24 4
gpt4 key购买 nike

我一直收到段错误,我从 char 指针知道它。但我想不通为什么?

Whiskey* createWhiskey(int a, double p, char* n){

Whiskey* whiskey = malloc(sizeof(Whiskey));
whiskey->age = a;
whiskey->proof = p;
whiskey->name = malloc((strlen(n)+1) * sizeof(char));
strcpy(whiskey->name, n);
return whiskey;
}
int main(){

Whiskey* burbon;
burbon = createWhiskey(12, 90.0, "MakersMark");

free(burbon);

return 0;
}

在 Alex 的评论中(见下文)添加了以下信息:

typedef struct{ int age; double proof; char* name; }Whiskey;

最佳答案

正如评论中所讨论的那样,显示的程序很好。

但是,您应该添加一些检查以避免出现问题。像这样的东西:

typedef struct{ int age; double proof; char* name; } Whiskey;

Whiskey* createWhiskey(int a, double p, char* n){
Whiskey* whiskey = malloc(sizeof(Whiskey));
if (whiskey)
{
whiskey->age = a;
whiskey->proof = p;
if (strlen(n) > SOME_MAXIMUM)
{
free(whiskey);
printf("Some error... maybe\n");
return NULL;
}
whiskey->name = malloc((strlen(n)+1) * sizeof(char));
if (whiskey->name)
{
strcpy(whiskey->name, n);
}
else
{
free(whiskey);
printf("Some error... \n");
return NULL;
}
}
return whiskey;
}

int main(){

Whiskey* burbon;
burbon = createWhiskey(12, 90.0, "MakersMark");
if (!burbon)
{
printf("Some error... \n");
}

// code....

if (burbon)
{
free( burbon->name);
free(burbon);
}
return 0;
}

关于c - 段错误,malloc 字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168807/

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