ravi_937's blog

By ravi_937, history, 2 years ago, In English

Here is the question_link
Here is my solution.
please guide me why my solution giving runtime error?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
2 years ago, # |
Rev. 2   Vote: I like it +3 Vote: I do not like it

Interesting. Running gdb with a random input of n=10k

Program received signal SIGSEGV, Segmentation fault.
comp (a1=..., a2=...) at x.cpp:5
5           if (a1[1] > a2[1]) {
Missing separate debuginfos, use: zypper install libgcc_s1-debuginfo-11.2.1+git1173-3.1.x86_64 libstdc++6-debuginfo-11.2.1+git1173-3.1.x86_64
(gdb) bt
#0  comp (a1=..., a2=...) at x.cpp:5
#1  0x0000000000402b49 in __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(std::array<long long, 3ul> const&, std::array<long long, 3ul> const&)>::operator()<__gnu_cxx::__normal_iterator<std::array<long long, 3ul>*, std::vector<std::array<long long, 3ul>, std::allocator<std::array<long long, 3ul> > > >, __gnu_cxx::__normal_iterator<std::array<long long, 3ul>*, std::vector<std::array<long long, 3ul>, std::allocator<std::array<long long, 3ul> > > > > (this=0x7fffffffda70, 
    __it1=<error reading variable: Cannot access memory at address 0x7ffff7485000>, __it2={_M_elems = {1, 1, 100001}})
    at /usr/include/c++/11/bits/predefined_ops.h:158
<-- snip -->
#7  0x0000000000401368 in solve () at x.cpp:19
#8  0x000000000040152f in main () at x.cpp:38

The issue is in your comparator. Removing it cures the program of the SIGSEGV. What also works is changing a1[1] > a2[1] to a1[1] >= a[2]. This stackoverflow answer explains the reason.


Edited to Add:

https://en.cppreference.com/w/cpp/algorithm/sort mentions less than for comparison function. You need a strict partial order.

comparison function object (i.e. an object that satisfies the requirements of Compare) which returns ​true if the first argument is less than (i.e. is ordered before) the second.

»
2 years ago, # |
Rev. 4   Vote: I like it 0 Vote: I do not like it

mach_vm_map(size=1152921513196781568) failed (error code=3) *** error: can't allocate region *** set a breakpoint in malloc_error_break to debug libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc

When i changed some parts of your code (not drastically) I've got this exception. To simplify it means that you ran out of memory at some stage. By doing some further research i came up to a conclusion that an error pops up at sorting with comparator stage.

Its a simple memory leak. You have to change your comparator and it'll most likely solve the problem. The above links will guide you.