力扣的坑,也是关于函数指针的问题
力扣的坑
做力扣的第一道题,题号350,两个数组的交集。
带尺寸的图片: ![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/201d25b9570230967d64ebc755a409e9.png)
就是一道简单题,可以用暴力法,也可以用双指针排序的方法,为了简单,就用了暴力法。
![codeblock](https://i-blog.csdnimg.cn/blog_migrate/d34d7e9f5e6bf1c701c398fa22a826fc.png)
感觉没问题,是吗?
错误代码:
45ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffdfc18dd4 at pc 0x0000004019fc bp 0x7fffdfc18c80 sp 0x7fffdfc18c70
WRITE of size 4 at 0x7fffdfc18dd4 thread T0
#2 0x7f5ba6fe682f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
Address 0x7fffdfc18dd4 is located in stack of thread T0 at offset 164 in frame
This frame has 6 object(s):
[32, 36) ‘size_1’
[96, 100) ‘size_2’
[160, 164) ‘ret_size’ <== Memory access at offset 164 overflows this variable
[224, 232) ‘nbytes’
[288, 296) ‘line’
[352, 356) ‘SEPARATOR’
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
(longjmp and C++ exceptions are supported)
Shadow bytes around the buggy address:
0x10007bf7b160: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b170: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b180: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b190: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b1a0: 00 00 00 00 00 00 f1 f1 f1 f1 04 f2 f2 f2 f2 f2
=>0x10007bf7b1b0: f2 f2 04 f2 f2 f2 f2 f2 f2 f2[04]f2 f2 f2 f2 f2
0x10007bf7b1c0: f2 f2 00 f2 f2 f2 f2 f2 f2 f2 00 f2 f2 f2 f2 f2
0x10007bf7b1d0: f2 f2 04 f2 f2 f2 00 00 00 00 00 00 00 00 00 00
0x10007bf7b1e0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b1f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x10007bf7b200: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
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
45ABORTING
一大堆的知识。一股离谱涌上心头。查了查,stack-buffer-overflow(栈溢出。没太理解。)
后来改了改,不用数组,改用指针的地址。
int* intersect(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize)
{
int i=0;
int * buffer = ( int * )malloc( sizeof( int ) * nums1Size );
*returnSize=0;
while(i<nums1Size)
{
for(int j=0;j<nums2Size;j++)
{
if(nums1[i]==nums2[j])
{
*( buffer + *returnSize ) = *( nums1 + i );
*returnSize += 1;
nums2[j]=-999;
break;
}
}
i++;
}
return buffer
}
改用指针buffer加偏移,就通过了。还没有搞清楚原因,可能就是简单题,要求严吧。
也欢迎小伙伴们不吝赐教。