1、我们经常使用的一个对临时字符串的分配如下:
Stu CreateStudent(char *student_name)
{
Stu s = (Stu)malloc(sizeof(Student));
s->age = 99;
s->name = (char *)malloc(strlen(student_name) + 1);
strcpy(s->name, student_name);
return s;
}
2、其实里面的这两句,完全可以使用strdup这个函数来代替
下面是完整的例子,和上面使用字符串分配+strcpy一样的结果
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
typedef struct Student
{
int age;
char *name;
}*Stu, Student;
//typedef Student* stu;
Stu CreateStudent(char *student_name)
{
Stu s = (Stu)malloc(sizeof(Student));
s->age = 99;
s->name = _strdup(student_name);
return s;
}
int main()
{
Stu point_studen;
point_studen = CreateStudent("zengraoli");
printf("student age is : %d, student name is : %s\n", point_studen->age, point_studen->name);
if (point_studen)
{
free(point_studen->name);
free(point_studen);
point_studen = NULL;
}
return 0;
}
3、strdup的一些描述
1)strdup()函数计算出字符串的长度,然后调用malloc()函数在堆上分配相应的空间
2)然后strdup()函数把所有字符复制到堆上的新空间
也就是说,strdup()总是在堆上创建空间,而不是在栈上,因为栈用来保存局部变量,而局部变量很快就会被清除
因为strdup()函数把新字符串放在堆上,所以最后需要释放对应的字符串.