realloc 调整动态内存开辟空间的大小
int* p1 = (int*)malloc(10 * sizeof(int));
if (p1 == NULL)
{
printf("%s", strerror(errno));
}
else
{
*p1 = 0x12345678;
*(p1 + 1) = 0x789;
}
free(p1);
p1 = NULL;

int *p1 = realloc(NULL,40); //可以当作malloc(40);使用
要避免:
对NULL进行解引用操作,
对动态开辟内存的越界访问
对非动态开辟的内存空间释放
使用free释放动态内存的一部分
对同一块动态内存多次释放
动态内存忘记释放(内存泄漏)
又是考题:


//第一种改正方式
void GetMemory(char **p)
{
*p = (char*)malloc(100);
}
void Test()
{
char *str = NULL;
GetMemory(&str);
strcpy(str,"Hello World");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
//第二种改正方式
char* GetMemory(char *p)
{
p = (char*)malloc(100);
return p;
}
void Test()
{
char *str = NULL;
str = GetMemory(str);
strcpy(str,"Hello World");
printf(str);
free(str);
str = NULL;
}
int main()
{
Test();
return 0;
}
又来一题:

返回栈空间地址
非法访问已出栈地址,VS:打印随机值
又来一题:

非法访问,但是输出world. 


柔性数组:

struct S* ps = (struct S*)malloc( sizeof(struct S)+5*sizeof(int) );
ps->n = 100; //
int i = 0;
for(i = 0; i < 5; i++)
{
ps->arr[i] = i;
}
struct S* ps2 = realloc(ps,44);
free(p1);
free(p2);