1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main(void) 5 { 6 int *p_old,*p_new,i; 7 8 p_old = (int *)malloc(2 * sizeof(int)); 9 *p_old = 1; 10 *(p_old + 1) = 2; 11 p_new = (int *)realloc(p_old,3 * sizeof(int)); 12 *(p_old + 2) = 3; 13 14 for(i = 0; i < 3; ++i) 15 printf("%d ",*(p_new + i)); 16 putchar(' '); 17 18 for(i = 0; i < 3; ++i) 19 printf("%d ",*(p_old + i));//point to the same memory area 20 putchar(' '); 21 22 for(i = 0; i < 3; ++i) 23 printf("%d ",p_old[i]);//as above 24 //free(p_old); 此处不需要释放 p_old,因为 realloc() 已经释放过了 25 free(p_new); 26 27 return 0; 28 }
结果:
1 2 3
1 2 3
1 2 3
realloc() should only be used for dynamically allocated memory. If the memory is not dynamically allocated, then behavior is undefined. https://www.geeksforgeeks.org/g-fact-66/
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int main(void) 5 { 6 int arr[2] = {1,2}; 7 int *p_old,*p_new; 8 9 for(int i = 0;i < 2; ++i) 10 printf("%d ",arr[i]); 11 p_old = arr; 12 p_new = (int *)realloc(p_old,3 * sizeof(int)); 13 arr[2] = 3; 14 for(int i = 0;i < 3; ++i) 15 printf("%d ",arr[i]); 16 free(p_old); 17 free(p_new); 18 19 return 0; 20 }
编译运行:
1 2
GDB 调试:
(gdb) l
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main(void)
5 {
6 int arr[2] = {1,2};
7 int *p_old,*p_new;
8
9 for(int i = 0;i < 2; ++i)
10 printf("%d ",arr[i]);
(gdb)
11 p_old = arr;
12 p_new = (int *)realloc(p_old,3 * sizeof(int));
13 arr[2] = 3;
14 for(int i = 0;i < 3; ++i)
15 printf("%d ",arr[i]);
16 free(p_old);
17 free(p_new);
18
19 return 0;
20 }
(gdb)
Line number 21 out of range; err_realloc.c has 20 lines.
(gdb) b 11
Breakpoint 1 at 0x4015f5: file err_realloc.c, line 11.
(gdb) r
Starting program: C:Usersluwudangcerr.exe
[New Thread 6188.0x1254]
[New Thread 6188.0x3e4]
1 2
Breakpoint 1, main () at err_realloc.c:11
11 p_old = arr;
(gdb) p p_old
$1 = (int *) 0x0
(gdb) p arr
$2 = {1, 2}
(gdb) p &arr[0]
$3 = (int *) 0x22fe30
(gdb) s
12 p_new = (int *)realloc(p_old,3 * sizeof(int));
(gdb) p p_old
$4 = (int *) 0x22fe30
(gdb) p p_new
$5 = (int *) 0x1c
(gdb) s
warning: Critical error detected c0000374
Program received signal SIGTRAP, Trace/breakpoint trap.
0x0000000077c1f3b0 in ntdll!RtlUnhandledExceptionFilter () from C:windowsSYSTEM32
tdll.dll
(gdb) p p_new
No symbol "p_new" in current context.