Heap-buffer-overflow返回动态分配块时的运行时错误



我最近开始用C编程,遇到了返回数组的问题。当我尝试返回数组时,我得到一个堆缓冲区溢出运行时错误。

我的代码

int* getConcatenation(int* nums, int numsSize, int* returnSize){
int *ans;
ans=(int*)malloc(numsSize * sizeof(int));
for (int i=0;i<numsSize;i++){
ans[i]=nums[i];
ans[i+numsSize]=nums[i];
}
free(ans);
return ans;
}

误差

AddressSanitizer: heap-buffer-overflow on address 0x60200000003c at pc 0x55780cb25d30 bp 0x7ffd83067af0 sp 0x7ffd83067ae0
WRITE of size 4 at 0x60200000003c thread T0
#2 0x7fabeed390b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x60200000003c is located 0 bytes to the right of 12-byte region [0x602000000030,0x60200000003c)
allocated by thread T0 here:
#0 0x7fabef97ebc8 in malloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10dbc8)
#3 0x7fabeed390b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
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 04 fa fa 00[04]fa fa fa fa 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
Shadow gap:              cc
==44==ABORTING

改变代码:

这是我现在的代码,但它仍然不能工作

int* getConcatenation(int* nums,
int numsSize, 
int* returnSize)
{
int *ans;
ans=malloc(2*numsSize * sizeof(int));
for (int i=0;i<numsSize;i++)
{
ans[i]=nums[i];
ans[i+numsSize]=nums[i];
}
return ans;
}

访问:

ans[i+numsSize]=nums[i];

远远超出了分配空间的界限。你需要;

ans = malloc(2 * numsSize * sizeof(int))

可以返回ans。您不能访问它所指向的内存,因为您使用free()将其返回到堆中。这使得它可以被重用。

即使free()被移除,在大多数情况下,这是一个不明智的模式。通过在函数内部分配内存,您将依赖于调用者知道内存必须是free'd。通常最好将分配置于与释放相同的作用域中(就像您所做的那样,但是在错误的作用域中)。更惯用的模式是让调用者提供内存并向函数传递一个指针。这样,内存甚至不需要动态分配,它在调用者的控制之下。

malloc()返回一个不需要强制转换的void*,这样做是不明智的做法。

最新更新