我编写了以下代码来清楚地了解 malloc 和 realloc。我已经使用 malloc 初始化指针,然后使用 realloc,我正在增加数组的大小。但是当我运行代码时出现以下错误。
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *p;
p = malloc(10);
p = " this is it";
printf("\n%s", p);
p = realloc(p, 14);
p[11] = 'A';
p[12] = 'B';
p[13] = 'C';
printf("\n %s", p) ;
return 0;
}
输出:
ajay@ajay-K54L:~$ gcc te.c
ajay@ajay-K54L:~$ ./a.out
*** glibc detected *** ./a.out: realloc(): invalid pointer: 0x000000000040071c ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7e626)[0x7fb111e88626]
/lib/x86_64-linux-gnu/libc.so.6(realloc+0x2de)[0x7fb111e8d3ee]
./a.out[0x4005dc]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fb111e2b76d]
./a.out[0x4004d9]
======= Memory map: ========
00400000-00401000 r-xp 00000000 08:03 3027043 /home/ajay/a.out
00600000-00601000 r--p 00000000 08:03 3027043 /home/ajay/a.out
00601000-00602000 rw-p 00001000 08:03 3027043 /home/ajay/a.out
00e76000-00e97000 rw-p 00000000 00:00 0 [heap]
7fb111bf4000-7fb111c09000 r-xp 00000000 08:03 2100801 /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb111c09000-7fb111e08000 ---p 00015000 08:03 2100801 /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb111e08000-7fb111e09000 r--p 00014000 08:03 2100801 /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb111e09000-7fb111e0a000 rw-p 00015000 08:03 2100801 /lib/x86_64-linux-gnu/libgcc_s.so.1
7fb111e0a000-7fb111fbd000 r-xp 00000000 08:03 2100780 /lib/x86_64-linux-gnu/libc-2.15.so
7fb111fbd000-7fb1121bc000 ---p 001b3000 08:03 2100780 /lib/x86_64-linux-gnu/libc-2.15.so
7fb1121bc000-7fb1121c0000 r--p 001b2000 08:03 2100780 /lib/x86_64-linux-gnu/libc-2.15.so
7fb1121c0000-7fb1121c2000 rw-p 001b6000 08:03 2100780 /lib/x86_64-linux-gnu/libc-2.15.so
7fb1121c2000-7fb1121c7000 rw-p 00000000 00:00 0
7fb1121c7000-7fb1121e9000 r-xp 00000000 08:03 2100760 /lib/x86_64-linux-gnu/ld-2.15.so
7fb1123d2000-7fb1123d5000 rw-p 00000000 00:00 0
7fb1123e5000-7fb1123e9000 rw-p 00000000 00:00 0
7fb1123e9000-7fb1123ea000 r--p 00022000 08:03 2100760 /lib/x86_64-linux-gnu/ld-2.15.so
7fb1123ea000-7fb1123ec000 rw-p 00023000 08:03 2100760 /lib/x86_64-linux-gnu/ld-2.15.so
7ffff08d4000-7ffff08f5000 rw-p 00000000 00:00 0 [stack]
7ffff09ff000-7ffff0a00000 r-xp 00000000 00:00 0 [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall]
this is itAborted (core dumped)
我在内存分配方面做错了什么?谢谢你。