讨论/算法和数据结构/简单面试题 10.01 归并两个有序数组,在clion里面通过了,但是为啥在leetcode oj会报内存错误呢/
简单面试题 10.01 归并两个有序数组,在clion里面通过了,但是为啥在leetcode oj会报内存错误呢

代码:
#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
void merge(vector<int>& A, int m, vector<int>& B, int n)
{ vector<int> tem(m,0);
for(int i=0;i<m;i++)
{
tem[i]=A[i];//just copy
}

     int p,q=0;int p_a=0;
     while(p<tem.size()&& q<B.size())
     {
         if(tem[p]<=B[q])
         {
             A[p_a]=tem[p];p++;p_a++;
         }
         else
             {A[p_a]=B[q];q++;p_a++;}


     }

         while(p!=tem.size())

          { A[p_a]=tem[p];p++;p_a++;

         }
         while(q!=B.size())

        { A[p_a]=B[q];q++;p_a++;

         }


}

};
int main()

{
vector<int> A = {1,2,3,0,0,0};int m = 3;
vector<int> B = {2,5,6}; int n = 3;
Solution s;
s.merge(A,m,B,n);

 for(int i=0;i<A.size();i++)
 {
     cout<<A[i]<<endl;
 }

std::cout << "Hello, World!" << std::endl;
return 0;

}

把main函数去掉后,就是提交到leetcode上面的

报错为:

=================================================================
==45==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000c0 at pc 0x00000038f1dd bp 0x7ffc10178c90 sp 0x7ffc10178c88
READ of size 4 at 0x6020000000c0 thread T0
#3 0x7f7eec31582f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
0x6020000000c0 is located 4 bytes to the right of 12-byte region [0x6020000000b0,0x6020000000bc)
allocated by thread T0 here:
#7 0x7f7eec31582f (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
Shadow bytes around the buggy address:
0x0c047fff7fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c047fff7fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c047fff7fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c047fff7ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x0c047fff8000: fa fa fd fa fa fa fd fa fa fa fd fa fa fa fd fa
=>0x0c047fff8010: fa fa 00 04 fa fa 00 04[fa]fa fa fa fa fa fa fa
0x0c047fff8020: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff8030: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff8040: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff8050: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c047fff8060: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==45==ABORTING

展开讨论

运行报错,是否有用例:m的值超过了A. size(),或者n也有此种情况?

展开全部 5 讨论