c - SIGABRT 为指针数组中的元素分配空间时

标签 c string gdb malloc valgrind

我试图在 c 中创建一个字符串数组,其中每个字符串都分配了正确数量的字符,但是,我收到以下错误:

sort: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

Program received signal SIGABRT, Aborted.
0x00007ffff7a42428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54

我在 GDB 中运行该程序,如果输入是:“this\nis\n”,则错误出现在第二行条目 ex 程序在处理"is"时失败。导致错误的行是

words[j]=(char *)malloc((i+1)*sizeof(char));

这里 words[j] 是位置 1 处的指针指针数组。'i' 是输入字符串中的字符数(在本例中输入是“is”,所以 i 是 2)。

我还通过 Valgrind 运行该程序,它在第一个单词处退出并显示以下错误消息:

==15272== Invalid write of size 8
==15272==    at 0x4C326CB: memcpy@@GLIBC_2.14 (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15272==    by 0x400A16: main (sort.c:59)
==15272==  Address 0x52064c0 is 0 bytes inside a block of size 5 alloc'd
==15272==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==15272==    by 0x4009AD: main (sort.c:54)
==15272== 

与 54 相关的代码行又是:

words[j]=(char *)malloc((i+1)*sizeof(char));

与 59 关联的行是:

memcpy(words[j],buffer,sizeof(buffer)+1);

其中 buffer 是一个大小为 1024 的数组,其中包含用户输入的字符串:“is\0”

根据要求,这里是更多的代码:

 char **words=malloc(1024*sizeof(*words));
 if(!words){
     perror("The word array could not be allocated in memory.");
     exit(7);
 }
 int word_count=0;
 char buffer[1024];
 c= ' ';
 for(int j=0;j<1024;j++){
     memset(buffer,0,sizeof(buffer));
     for(int i=0;i<1024;i++){
         c=getchar();
         if(c==EOF || c== '\n'){
             //printf("c is %c buffer is %s\n",c,buffer);
             buffer[i]='\0';
             word_count++;
             words[j]=(char *)malloc((i+1)*sizeof(char));
             if(!words[j]){
             perror("The word could not be allocated in memory.");
             exit(7);
             }
             memcpy(words[j],buffer,sizeof(buffer)+1);
             words[j][sizeof(buffer)+1]='\0';
             break;
         }
         buffer[i]=c;
     }
     if(c==EOF){
         break;
     }
     else continue;
 }
 }

最佳答案

The line associated with 59 is:

memcpy(words[j],buffer,sizeof(buffer)+1);

Where buffer is an array of size 1024 containing the user input string: "is\0"

这是错误。 sizeof(buffer)+1 为 1025;无论输入字符串的长度如何,您都在复制 1025 个字符。您只为 i+1 个字符分配了空间,因此 i+1 个字符是您应该复制的数量。

关于c - SIGABRT 为指针数组中的元素分配空间时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49832586/

相关文章:

c - scanf() 不接受任何输入

有人可以澄清这段代码吗?

C/汇编子程序段错误

javascript - 使用字符串创建变量

Python - 将字符串拆分为参数

c - 如何调试嵌入式应用程序中的内存问题

c - 创建后我怎么能记住树的根

c - 如何使用 pthreads 在 C 中的 udpclient 中发送和接收

string - 内存中字符串去重

c++ - 数组索引越界,但 gdb 报告错误行 - 为什么?