我正在尝试一个例子
int main(){
int count = 5;
char *a = "JOSUA";
char *c = "JANETALAE";
char *b = NULL;
char *d = NULL;
b = (char *)malloc(sizeof(char)*5);
b = a;
if(b == NULL){
printf("\n malloc failed");
}
printf("\nChar is:%s\n",b);
d = (char *)realloc(b,sizeof(char) * 9);
if(d == NULL){
printf("\n realloc failed");
}
else{
b = d;
b = c;
}
printf("\nChar is:%s\n",b);
return 0;
}
我正在尝试一个示例程序来分配和重新分配内存。但是我无法重新分配内存并获得编译中断,如下所示。
Char is:JOSUA
*** glibc detected *** ./realloc: realloc(): invalid pointer: 0x080485b4 ***
======= Backtrace: ========= /lib/libc.so.6[0x88ffd1] /lib/libc.so.6(realloc+0x2cf)[0x89613f] /lib/libc.so.6(realloc+0x2e7)[0x896157] ./realloc[0x80484aa] /lib/libc.so.6(__libc_start_main+0xe6)[0x836e16] ./realloc[0x8048391]
======= Memory map: ======== 007fc000-0081c000 r-xp 00000000 fd:00 659977 /lib/ld-2.12.90.so 0081c000-0081d000 r--p 0001f000 fd:00 659977 /lib/ld-2.12.90.so 0081d000-0081e000 rw-p 00020000 fd:00 659977 /lib/ld-2.12.90.so 00820000-009ad000 r-xp 00000000 fd:00 660018 /lib/libc-2.12.90.so 009ad000-009af000 r--p 0018c000 fd:00 660018 /lib/libc-2.12.90.so 009af000-009b0000 rw-p 0018e000 fd:00 660018 /lib/libc-2.12.90.so 009b0000-009b3000 rw-p 00000000 00:00 0 00a29000-00a45000 r-xp 00000000 fd:00 660039 /lib/libgcc_s-4.5.1-20100924.so.1 00a45000-00a46000 rw-p 0001b000 fd:00 660039 /lib/libgcc_s-4.5.1-20100924.so.1 00a84000-00a85000 r-xp 00000000 00:00 0 [vdso] 08048000-08049000 r-xp 00000000 fd:02 9440701 /home/user/beata/c_samples/realloc 08049000-0804a000 rw-p 00000000 fd:02 9440701 /home/user/beata/c_samples/realloc 092ac000-092cd000 rw-p 00000000 00:00 0 [heap] b78bc000-b78bd000 rw-p 00000000 00:00 0 b78d3000-b78d5000 rw-p 00000000 00:00 0 bfbd8000-bfbf9000 rw-p 00000000 00:00 0 [stack] Aborted (core dumped)
无法理解为什么会发生编译中断。