错误未解决:Leetcode 上的 heap-buffer-overflow

the error not resolved: heap-buffer-overflow on Leetcode

我的代码如下:

int* smallerNumbersThanCurrent(int* nums, int numsSize, int* returnSize){
    int count;
    int* out = malloc(500);
    int i, j;

    for(i = 0; i < numsSize; ++i){
        count = 0;
        for(j = 0; j < numsSize; ++j){
            if(nums[i] > nums[j]){
                count++;
            }
        }
        *(out + i) = count;
    } 

    return out;
}

错误信息如下

实际上,当我在 Leetcode 上解决问题时,这个 heap-buffer-overflow 一直出现。即使它在 Mac.

的终端中运行良好

将不胜感激任何评论或帮助!

因为我认为这是作业,所以我只通过查看代码描述直接想到的内容:

首先,您在堆上分配了一个 500 字节的缓冲区 (malloc(500)),此时您还不知道确切的大小。此外,您不检查 malloc return 是否为 NULL 指针。我会将此行更改为 calloc(numsSize, sizeof(*out)),因为结果数组在最坏情况下与输入数组的大小相同。同时添加对 return 值的检查。

第二件事是你传入了一个变量来保存结果计数,但没有给它赋值。没有此信息,调用者无法知道结果数组中有多少元素是有效的。

起初,您没有检查 malloc 函数。

其次,这个函数没有使用参数returnSize

如果numsSize > (500/ sizeof(int))

,您的功能将失败

也许下面的代码可以帮到您

int* smallerNumbersThanCurrent(int* nums, int numsSize){
   int count;
   int* out = malloc(numsSize * sizeof(int));
   if (out) {
       fprintf(stderr, "%s: malloc failed\n", __func__);
       exit(EXIT_FAILURE);
   }

   for(int i = 0; i < numsSize; ++i){
       count = 0;
       for(int j = 0; j < numsSize; ++j){
            if(nums[i] > nums[j]){
               count++;
            }
       }
      *(out + i) = count;
  } 

   return out;
}