?1 系统函数realloc测试
? ? mac OS 系统 函数解释
? ? The realloc() function tries to change the size of the allocation pointed ? ? ?to by ptr to size, and returns ptr. ?If there is not enough room to ? ? ?enlarge the memory allocation pointed to by ptr, realloc() creates a new ? ? ?allocation, copies as much of the old data pointed to by ptr as will fit ? ? ?to the new allocation, frees the old allocation, and returns a pointer to ? ? ?the allocated memory. ?If ptr is NULL, realloc() is identical to a call ? ? ?to malloc() for size bytes. ?If size is zero and ptr is not NULL, a new, ? ? ?minimum sized object is allocated and the original object is freed. ?When ? ? ?extending a region allocated with calloc(3), realloc(3) does not guaran- ? ? ?tee that the additional memory is also zero-filled.
#include <stdio.h>
#include <stdlib.h>
typedef char *sds;
int main() {
printf("Hello, World!\n");
char t[] = {'a','b','c','d'};
sds s = t+1;
char bb = s[0];
char cc = s[1];
char dd = s[2];
char flag = *(s - 1);
printf("%c %c %c %c", flag, bb, cc ,dd);
int * p=NULL;
p=(int *)malloc(sizeof(int));
*p=3;
printf("\np=%p\n",p);
printf("*p=%d\n",*p);
// 空间不变
p=(int *)realloc(p,sizeof(int));
printf("p=%p\n",p);
printf("*p=%d\n",*p);
// 空间扩大三倍,同时内容会被复制(内存足够的情况下,起始地址不变)
p=(int *)realloc(p,3*sizeof(int));
printf("p=%p\n",p);
printf("*p=%d",*p);
//释放p指向的空间
realloc(p,0);
p=NULL;
return 0;
}
2 结果:
Hello, World! a b c d
p=0x7fa656405b50 *p=3 p=0x7fa656405b50 *p=3 p=0x7fa656405b50? // 扩容后起始地址没有变化(内存足够) *p=3 Process finished with exit code 0
3 小结
函数:void * realloc(void * p,int n);
// 指针p必须为指向堆内存空间的指针,即由malloc函数、calloc函数或realloc函数分配空间的指针。
// realloc函数将指针p指向的内存块的大小改变为n字节。如果n小于或等于p之前指向的空间大小,
// 那么。保持原有状态不变。如果n大于原来p之前指向的空间大小,那么,系统将重新为p从堆上
// 分配一块大小为n的内存空间,同时,将原来指向空间的内容依次复制到新的内存空间上,
// p之前指向的空间被释放。relloc函数分配的空间也是未初始化的。
|