简体   繁体   中英

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.

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).

I've used two counters, i and j, "i" is counter of the original vector, and "j" is counter of vector "result". 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 . Imagine what would happen if size was 3:

  1. At first, you have i=0,j=0; .
  2. result[0] = vect[0]+vect[1];
  3. j++ . j is now 1.
  4. i+=2; . i is now 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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