realloc函数
概要:
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
描述:
该函数释放参数ptr指向的旧对象,并返回指向具有参数size指定大小的新对象的指针。如果新分配的内存不大于原先内存,新内存的内容与原先内存的内容相同;如果新分配的内存大于原先内存,超出部分的内容是不确定的。
如果参数ptr是空指针,realloc函数将像malloc函数一样分配指定大小的内存。如果参数ptr不能匹配先前内存管理函数返回的指针,或者如果参数ptr指向的内存已经被释放,或者如果参数size值为0,函数行为是未定义的。
如果参数size是非0值,并且未给新对象分配内存,则不会释放旧对象的内存;如果旧对象未被释放,其值应保持不变。
参数:
void *ptr
指向原先分配内存的指针。
size_t size
指定新分配内存大小的size_t类型整数。
返回值:
函数返回指向新对象的指针(它可能与指向旧对象的指针具有相同的值。);如果新对象的内存未能分配,函数返回空指针。
范例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
/*函数realloc范例*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *str, *ptr;
int size, i, ch;
puts("Input the size of the string.");
if((scanf("%d", &size) != 1)|| (size <= 0))
{
puts("Invalid input.");
return EXIT_FAILURE;
}
/*清空输入缓冲区。*/
while(((ch = getchar()) != '\n') && (ch != EOF))
;
/*分配内存。*/
str = malloc(size);
if(str == NULL)
{
puts("Memory allocation failed.");
return EXIT_FAILURE;
}
puts("Input the string.");
/*向分配的内存中写入内容。*/
for(i=0;i<(size-1);++i)
{
ch = getchar();
if((ch == '\n') || (ch == EOF))
{
break;
}
str[i] = ch;
}
str[i] = '\0';
/*重新分配内存。*/
ptr = realloc(str, (size+50));
if(ptr == NULL)
{
puts("Memory allocation failed.");
free(str);
return EXIT_FAILURE;
}
str = ptr;
puts("Input new string.");
/*在str内容后输入新内容。*/
str[i++] = ' ';
for(;i<(size+50-1);++i)
{
ch = getchar();
if((ch == '\n') || (ch == EOF))
{
break;
}
str[i] = ch;
}
str[i] = '\0';
puts(str);
/*释放内存。*/
free(ptr);
return 0;
}
|
结果:
假设输入为:
100
It is hard to fail, but it is worse never to have tried to succeed.
-Theodore Roosevelt
将输出:
It is hard to fail, but it is worse never to have tried to succeed. -Theodore Roosevelt
相关内容:
主要参考资料:
1、ISO/IEC 9899:2024
2、ISO/IEC 9899:2018