单独molloc
/*
小知识1: const char *
const char* str 定义的是一个指向常量的指针。
如果str是局部变量,则字符串会随着变量所在的函数的退出而自动释放;
如果str是全局变量,则程序退出时才自动释放。
小知识2: strdup底层实现 -- 要自己释放,不推荐使用
char * __strdup (const char *s)
{
size_t len = strlen (s) + 1;
void *new = malloc (len);
if (new == NULL)
return NULL;
return (char *) memcpy (new, s, len);
}
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define NAME_MAX 128
typedef struct test_struct{
const char * name;
int id;
int account;
} test_struct_t;
test_struct_t * test_struct_malloc_error_example() {
// 下面这种申请结构的方法不对,正确方法见 test_struct_malloc()
test_struct_t * test = (test_struct_t *)malloc(NAME_MAX + 1 + sizeof(test_struct_t));
return test;
}
static test_struct_t * test_struct_malloc(){
test_struct_t *stat_item = NULL;
stat_item = (test_struct_t *)malloc(sizeof(test_struct_t));
assert(stat_item);
stat_item->name = (char *)malloc(NAME_MAX + 1);
assert(stat_item->name);
return stat_item;
}
int main() {
char * test_name = "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkdasldjlasdjlsdjalsdjaslkdjlsadkjasldjasldjasldkjaslkdjasldjasldjasldjaslkdjasldjalsdjaslkdjaskldkjasldkjaslkdjaslkdjasld";
// memcpy会报段错误
// test_struct_t * test = test_struct_malloc_error_example();
// 正确方法malloc,memcpy不会报段错误
test_struct_t * test = test_struct_malloc();
// strdup配合const char * 使用,const char * 会在自己的定义域结束自己释放,当然也可自己主动释放
// 如果不配合const char * 使用,则需要自己手动释放 test->name,否则会造成内存泄露
// test->name = strdup(test_name);
memcpy(test->name, test_name, NAME_MAX);
test->id = 1;
test->account = 123232;
printf("test->name = %s\n", test->name);
printf("test->id = %d\n", test->id);
printf("test->account = %d\n", test->account);
free((char *)test->name);
free(test);
return 0;
}
使用strdup(不推荐)
我们定义的字符串指针是没有内存空间的,需要先申请空间之后再赋值,于是就发现了这样一个字符串函数:strdup(str);
strdup()函数会计算出字符串的长度,然后调用malloc函数在堆上申请相应的空间,最后把字符串的所有字符复制到堆上
i.e.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct test_struct
{
const char * name;
int id;
int account;
} test_struct_t;
int main() {
char * test_name = "jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjkdasldjlasdjlsdjalsdjaslkdjlsadkjasldjasldjasldkjaslkdjasldjasldjasldjaslkdjasldjalsdjaslkdjaskldkjasldkjaslkdjaslkdjasld";
test_struct_t * test = malloc(sizeof(test_struct_t));
// test_struct_t * test = (test_struct_t *)malloc(sizeof(test_name) + 1 + sizeof(test_struct_t));
// memcpy(test->name, test_name, strlen(test_name)+1);
test->name = strdup(test_name);
test->id = 1;
test->account = 123232;
printf("test->name = %s\n", test->name);
printf("test->id = %d\n", test->id);
printf("test->account = %d\n", test->account);
return 0;
}