我一直遇到分段错误,我从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;
答案 0 :(得分:1)
正如评论中所讨论的,所显示的程序很好。
但是,您应该添加一些检查以避免出现问题。类似的东西:
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;
}
答案 1 :(得分:1)
我希望你的威士忌结构的定义很好。以下代码对我来说很好:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Whisk {
int age;
double proof;
char *name;
} Whiskey;
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");
if (!burbon)
{
printf("Some error... \n");
}
// code....
if (burbon)
{
free( burbon->name);
free(burbon);
}
return 0;
}
答案 2 :(得分:0)
以下代码
free()
代码:
#include <string.h> // malloc()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <stdio.h> // perror()
typedef struct
{
int age;
double proof;
char* name;
} Whiskey;
Whiskey* createWhiskey(int age, double proof, char* name)
{
Whiskey* whiskey = NULL;
if( NULL == (whiskey = malloc(sizeof(Whiskey)) ) )
{ // then, malloc failed
perror( "malloc for Whiskey failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
whiskey->age = age;
whiskey->proof = proof;
whiskey->name = NULL;
if( NULL == (whiskey->name = malloc( strlen(name)+1) ) )
{ // then malloc failed
perror( "malloc for name field failed" );
free( whiskey );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
strcpy(whiskey->name, name);
return whiskey;
} // end function: createWhiskey
int main( void )
{
Whiskey* burbon;
burbon = createWhiskey(12, 90.0, "MakersMark");
free( burbon->name );
free( burbon );
return 0;
} // end function: main