简体   繁体   中英

stack around array variable corrupted

i am trying to pass my array through my assign and draw functions. the assign function only exists to take the wins array and assign a value of 0 for all of the elements in the array. my draw function fills the array with random numbers 1-100 with 20 numbers in the array. when i try to compile i end up with a runtime error stating that the stack around my variable (array) wins is corrupted. where should i go from here?

#include<iostream>
#include <ctime>

using std::cout; using std::cin; using std::endl;

void draw(int a[]);
void assign(int a[]);
int sizeofarray = 20;


int main() {
    int wins[20] = {};

    assign(wins);

    cout << "compiled!" << endl;

}

void assign(int a[20]) {

    a[20] = {};
    draw(a);

}

void  draw(int a[])

{
    srand(time(nullptr));
    int rannum = (1 + rand() % 100);


    for (int i = 0; i < 20; i++) {

        a[i] = 1 + rand() % 100;
    }


}

When you get an error with information as helpful as this, you should immediately be thinking "I have a buffer overflow". Then go looking for it.

Sure enough, here it is:

void assign(int a[20]) {
    a[20] = {};            // <--- BOOM!
    draw(a);
}

Your array can only store 20 elements. When you store something at the 21st element, you have undefined behavior.

Just adding some more information here. It's possible that you thought the offending line would zero-initialize the entire array (like it does when defining the variable). However, outside of an array definition, this is not the case. a[20] = {} is an assignment.

If you wish to zero the array, use std::fill as follows:

std::fill(a, a+20, 0);

I should point out, however, that there's no point zeroing the array in the context of your code as written. It's already zeroed on entry, and the draw function initializes every element anyway.

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