gpt4 book ai didi

在 C 中重新分配内存时编译中断

转载 作者:太空狗 更新时间:2023-10-29 15:51:02 24 4
gpt4 key购买 nike

我正在尝试一个例子

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)

无法理解为什么会发生编译中断。

最佳答案

您不能在静态内存变量(实际上是 a)上使用 realloc:

b = (char *)malloc(sizeof(char)*5);
b = a;

关于在 C 中重新分配内存时编译中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com