SIGABRT When Mallocing Space for Element in Pointer Array

SIGABRT When Mallocing Space for Element in Pointer Array

我试图在 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);

其中缓冲区是包含用户输入字符串的大小为 1024 的数组:"is[=36=]"

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

 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]='[=16=]';
             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]='[=16=]';
             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[=14=]"

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