user3142453
user3142453

Reputation: 87

Munmap_chunk() error, cannot understand pointer behavior

I am making a simple sorting program with templates and are struggling with string case. Code:

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;
}

So this is working wonderful for integers. And it is working for strings as long as I remove the "delete joined" line, but that is pretty crucial for sorting large arrays. GDB backtrace log:

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

I think this is probably caused by std::string assignment magic but I can't figure out how to fix it. Tried a lot of things like casting right hand side of assigment to (const typ&) so it will copy it according to that documentation but it's still trying blindly. Could anyone help me with this?

I can provide full code but it's not visually identical (english is not my native language and I changed functions/var names here) so it may be harder to read.

Thanks!

Upvotes: 0

Views: 344

Answers (1)

Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11944

You should use delete[] since you are deleting an array allocated with new[]. Mixing incorrect types of new/delete can lead to undefined behavior according to the standard which I guess is what you are seeing.

Upvotes: 1

Related Questions