二级指针堆内存模型--字符串赋值易错点
内存模型图:
当DEBUG为1时直接修改了堆中的内存指向,造成了内存泄漏,而且在free的时候会free常量区直接报错,最好的办法就是用内存拷贝函数执行字符串赋值操作,避免指针指向常量区,造成程序出现bug。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define DEBUG 0
void assignValueTest(char **myp, int num)
{
printf("enter Func assignValueTest!\n");
for (size_t i = 0; i < num; i++)
{
#if DEBUG == 0
printf("赋值之前的myp地址:%p\n", myp[i]);
myp[i] = "1234";
printf("常量区字符串“1234”的地址%p\n", "1234");
printf("赋值之后的myp地址:%p\n", myp[i]);
printf("---------------------------------------------------\n");
#else
strcpy(myp[i], "1234");
#endif
}
}
int creatMem(char ***myp, int num)
{
char **p = NULL;
p = *myp;
p = (char **)malloc(sizeof(char*) *num);
if (p == NULL)
{
printf("Func creatMem malloc failure\n");
return -1;
}
for (size_t i = 0; i < num; i++)
{
p[i] = (char *)malloc(sizeof(char) *num);
if(p[i] == NULL)
{
printf("Func creatMem malloc failure\n");
return -2;
}
}
assignValueTest(p, num);
*myp = p;
return 0;
}
void freeMem(char ***myp, int num)
{
printf("enter Func freeMem!\n");
char **p = NULL;
p = *myp;
for (int i=0; i < num; i++)
{
if (p[i] != NULL)
{
free(p[i]);
p[i] = NULL;
}
}
if (p != NULL)
{
free(p);
}
*myp = NULL;
printf("Func freeMem run successfuly\n");
}
void printDate(char **myp, int num)
{
for (int i = 0; i < num; i++)
{
printf("%s\n", myp[i]);
}
}
int main()
{
int num = 5;
char **p = NULL;
int ret = 0;
ret = creatMem(&p, num);
if(ret != 0)
{
printf("Func creatMem malloc failure\n");
return -1;
}
printDate(p, num);
freeMem(&p, num);
return 0;
}
当DEBUG=1时的结果:
[[email protected] heima]$ ./a.out
enter Func assignValueTest!
赋值之前的myp地址:0x1c96040
常量区字符串“1234”的地址0x400a91
赋值之后的myp地址:0x400a91
---------------------------------------------------
赋值之前的myp地址:0x1c96060
常量区字符串“1234”的地址0x400a91
赋值之后的myp地址:0x400a91
---------------------------------------------------
赋值之前的myp地址:0x1c96080
常量区字符串“1234”的地址0x400a91
赋值之后的myp地址:0x400a91
---------------------------------------------------
赋值之前的myp地址:0x1c960a0
常量区字符串“1234”的地址0x400a91
赋值之后的myp地址:0x400a91
---------------------------------------------------
赋值之前的myp地址:0x1c960c0
常量区字符串“1234”的地址0x400a91
赋值之后的myp地址:0x400a91
---------------------------------------------------
1234
1234
1234
1234
1234
enter Func freeMem!
Segmentation fault (core dumped)
[[email protected] heima]$