数组变量周围的堆栈损坏 [英] stack around array variable corrupted

查看:166
本文介绍了数组变量周围的堆栈损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过我的assign和draw函数传递数组.仅存在分配函数以获取wins数组并为该数组中的所有元素分配一个值为0的值.我的绘制函数使用数组中的20个数字用随机数1-100填充数组.当我尝试编译时,我最终遇到运行时错误,指出我的变量(数组)wins周围的堆栈已损坏.我应该从这里去哪里?

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.

果然,这里是:

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

您的数组只能存储20个元素.当您将内容存储在21st元素上时,您将具有未定义的行为.

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

只需在此处添加更多信息即可.您认为有问题的行会将整个数组归零(这是在定义变量时所做的事情),这是可能.但是,在数组定义之外,情况并非如此. a[20] = {}是一项作业.

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.

如果您希望将数组归零,请按以下方式使用std::fill:

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

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

但是,我应该指出,在编写的代码上下文中将数组归零是没有意义的.输入时它已经为零,并且draw函数无论如何都会初始化每个元素.

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.

这篇关于数组变量周围的堆栈损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆