Munmap_chunk() 错误,无法理解指针行为

Munmap_chunk() error, cannot understand pointer behavior

本文关键字:指针 chunk 错误 Munmap      更新时间:2023-10-16

我正在使用模板制作一个简单的排序程序,并且正在努力解决字符串大小写。法典:

template<typename typ>
void Join_Segments(typ *tab, int begin1, int begin2, int end2, bool(*Compare)(typ arg1, typ arg2)){
  typ *joined = new typ[end2-begin1+1]; // sorted elements arrray
  int c1, c2, ci;                        // counters
  for(c1=begin1, c2=begin2, ci=0; c1<begin2 && c2<=end2; ci++){         
    if(!Compare(tab[c1], tab[c2])){ joined[ci]=tab[c2]; c2++;}
    else{ joined[ci]=tab[c1]; c1++;}
  }
  while(c1<begin2){joined[ci]=tab[c1]; c1++; ci++;}
  while(!(c2>end2)){joined[ci]=tab[c2]; c2++; ci++;}
  for(int i=0; i<(end2-begin1+1); i++) tab[begin1+i]=joined[i];
  delete joined;
}

所以这对整数来说效果很好。只要我删除"删除连接"行,它就可以用于字符串,但这对于对大型数组进行排序非常重要。GDB 回溯日志:

Program terminated with signal SIGABRT, Aborted.
#0  0x40022424 in __kernel_vsyscall ()
(gdb) bt
#0  0x40022424 in __kernel_vsyscall ()
#1  0x40171827 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0x40174c53 in __GI_abort () at abort.c:89
#3  0x401ac993 in __libc_message (do_abort=do_abort@entry=1, 
    fmt=fmt@entry=0x402a9a5c "*** Error in `%s': %s: 0x%s ***n")
    at ../sysdeps/posix/libc_fatal.c:175
#4  0x401b6e7a in malloc_printerr (action=<optimized out>, 
    str=0x402a9a80 "munmap_chunk(): invalid pointer", ptr=0x90551d4)
    at malloc.c:4996
#5  0x401b6f48 in munmap_chunk (p=<optimized out>) at malloc.c:2816
#6  0x400849df in operator delete(void*) ()
   from /usr/lib/i386-linux-gnu/libstdc++.so.6
#7  0x08049518 in Join_Segments<std::string> (tab=0x905500c, begin1=0, begin2=2, 
    end2=2, Compare=0x80490a6 <_GLOBAL__sub_I__Z2Nli()+8>) at scalanie.hh:11
#8  0x080491f5 in Mergesort<std::string> (tab=0x905500c, begin=0, 
    end=2, Compare=0x80490a6 <_GLOBAL__sub_I__Z2Nli()+8>) at scalanie.hh:32
#9  0x08048ee1 in main () at main.cpp:11

我认为这可能是由 std::字符串赋值魔法引起的,但我无法弄清楚如何解决它。尝试了很多东西,例如将 assigment 的右侧转换为 (const typ&),因此它会根据该文档复制它,但它仍在盲目尝试。谁能帮我解决这个问题?

我可以提供完整的代码,但它在视觉上并不相同(英语不是我的母语,我在这里更改了函数/var 名称),因此可能更难阅读。

谢谢!

您应该

使用delete[],因为您要删除分配有new[]的数组。根据标准,混合不正确类型的new/delete可能会导致未定义的行为,我想这就是您所看到的。