简体   繁体   English

我有一个意外的缓冲区溢出警告,为什么会这样?

[英]I have an unexpected buffer overrun warning, why do I have that?

I have to create a function that sum components of a vector this way:我必须以这种方式创建一个对向量的分量求和的函数:

  • first + second,第一个+第二个,
  • third + fourth,第三+第四,
  • 5th + 6th, and so on.第 5 次 + 第 6 次,依此类推。

original vector has size "size".原始向量的大小为“大小”。 I have to create a result vector dynamically with size "size/2", (because doing sum this way I've halved the original vector size).我必须动态创建一个大小为“size/2”的结果向量(因为以这种方式求和,我将原始向量大小减半)。

I've used two counters, i and j, "i" is counter of the original vector, and "j" is counter of vector "result".我使用了两个计数器,i 和 j,“i”是原始向量的计数器,“j”是向量“结果”的计数器。 I think the problem is here, because I have a buffer overrun warning.我认为问题就在这里,因为我有一个缓冲区溢出警告。

this is my code:这是我的代码:

#include <stdint.h>
#include <stdlib.h>


uint32_t* add_twobytwo(uint32_t* vect, size_t size) {
    if (vect == NULL) {
        return NULL; 
    }
    uint32_t* result = malloc((size / 2) * sizeof(uint32_t)); 
    if (result == NULL) {
        return NULL; 
    }
    size_t j = 0; 
    for (size_t i = 0; i < size; i += 2) {
        result[j] = vect[i] + vect[i + 1]; 
        j++; 
    }

    return result; 
}


int main(void)
{
    size_t n = 6;
    uint32_t* v = malloc(n * sizeof(uint32_t));
    if (v == NULL) {
        return NULL; 
    }
    v[0] = 3; v[1] = 87; v[2] = 5; v[3] = 7; v[4] = 12; v[5] = 9;
    uint32_t* sum = add_twobytwo(v, n);
    free(v);
    free(sum);
    return 0;
}

green squiggle is located here:绿色曲线位于此处:

  for (size_t i = 0; i < size; i += 2) {
            result[j] = vect[i] + vect[i + 1]; 
            j++; 
        }

I've tried to interpret the warning, and it seems that there isn't enough space in result[], but it's working properly and it does its job correctly (I've debugged line-by-line to state this).我试图解释警告,结果 [] 中似乎没有足够的空间,但它工作正常并且它正确地完成了它的工作(我已经逐行调试来说明这一点)。

You get a warning, because if size were odd, then you would be reading elements past the end of vect .您会收到警告,因为如果size是奇数,那么您将在vect末尾阅读元素。 Imagine what would happen if size was 3:想象一下如果 size 为 3 会发生什么:

  1. At first, you have i=0,j=0;一开始,你有i=0,j=0; . .
  2. result[0] = vect[0]+vect[1];
  3. j++ . j++ j is now 1. j 现在是 1。
  4. i+=2; . . i is now 2.我现在是 2。
  5. result[1] = vect[2]+vect[3];

However, because vect has a size of 3, trying to read vect[3] (which you are), will (most likely) produce a segmentation fault.但是,由于vect的大小为 3,因此尝试读取vect[3] (您是)将(很可能)产生分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM