这可能会花很长时间,但实际上我要尝试的是连接两个整数数组:[1,2]
和[3,4]
,以便结果为[1,2,3,4]
。
我的代码是我对此leetcode problem提出的解决方案。
这是我的代码:
#include <stdio.h>
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size) {
int totalLen = nums1Size + nums2Size;
int halflen = totalLen/2;
int INTSIZE = sizeof(int);
int* arr = malloc(INTSIZE*totalLen);
int c1 = 0;
int c2 = 0;
// loop through lists to combine them into a sorted array
for (int i = 0; i < halflen+1; i++) {
if (nums1[c1] > nums2[c2]) {
arr[i] = nums2[c2];
c2++;
} else {
arr[i] = nums1[c1];
c1++;
}
// PART THAT BREAKS
// If we've exhausted all of nums1, concat nums2 to the end of it
if (c1 >= nums1Size) {
memcpy(arr+(i*INTSIZE), nums2, INTSIZE*(nums2Size-c2));
break;
}
}
// find and return median
if ((int)halflen < halflen) {
return (arr[halflen] + arr[halflen-1]) / 2;
} else {
return arr[halflen];
}
}
有人可以解释我做错了什么以及如何解决吗?给我的错误是:
=================================================================
==30==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000070 at pc 0x7fbe96801784 bp 0x7ffff6c07570 sp 0x7ffff6c06d20
WRITE of size 8 at 0x602000000070 thread T0
#0 0x7fbe96801783 (/usr/local/lib64/libasan.so.5+0x3e783)
#4 0x7fbe954212e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
Address 0x602000000070 is a wild pointer.
SUMMARY: AddressSanitizer: heap-buffer-overflow (/usr/local/lib64/libasan.so.5+0x3e783)
Shadow bytes around the buggy address:
0x0c047fff7fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
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 00 fa fa fa 00 fa fa fa 00 00 fa fa[fa]fa
0x0c047fff8010: fa fa fa fa fa fa fa fa 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
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
==30==ABORTING
(不幸的是,我也不知道这个错误试图告诉我多少)
答案 0 :(得分:0)
您在memcpy
中计算的地址有误。由于arr
为int *
,因此您要添加许多整数来推进指针,而不是一定数量的字节。
一种解决方法是让编译器计算地址:
memcpy(&arr[i], &nums2[c2], INTSIZE*(nums2Size-c2));
或者,坚持使用指针数学,
memcpy(arr + i, nums2 + c2, INTSIZE*(nums2Size-c2));
最后一个参数是要复制的字节数,因此需要将整数计数修改为字节数。
在两种情况下,我都调整了第二个参数以从nums2
数组中的正确元素开始复制。
然后问自己:如果c2
到达nums2Size
会发生什么?您目前不处理这种情况。