简体   繁体   English

写入“array”时缓冲区溢出:可写大小为“1*4”字节,但可能写入“8”字节

[英]Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written

I am filling an empty array with randomly generated numbers between 0 and 100000 but the line "array[i] = rand() % 100000;"我正在用 0 到 100000 之间的随机生成的数字填充一个空数组,但行“array[i] = rand() % 100000;” has a green underline and says "Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written".有一条绿色下划线,并表示“写入‘数组’时缓冲区溢出:可写大小为‘1*4’字节,但可能写入‘8’字节”。 Does anyone know how to fix this?有谁知道如何解决这一问题?

#include <iostream>
#include <Windows.h>
#include <time.h>
#pragma

using namespace std;

int main() {

    int N;
    cout << "Enter a value for N: ";
    cin >> N;
    int* array = new int(N);
    srand(time(0));
    for (int i = 0; i < N; i++) {
        array[i] = rand() % 100000;
    }

    for (int i = 0; i < N; i++) {
        cout << array[i] << ", ";
    }

    delete array;
    return 0;
}

new int(N); creates a single int with the initial value N .创建一个具有初始值N单个int

For an array, write new int[N];对于一个数组,写new int[N];

To free this memory you need to write delete[] array;要释放这个 memory 你需要写delete[] array; : the behaviour of delete array; delete array; will be undefined.将是未定义的。

Note that a drop-in replacement that takes care of all the memory management for you would be请注意,为您处理所有 memory 管理的直接替换将是

std::vector<int> array(N);

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

相关问题 错误:C6386:写入“newArr”时缓冲区溢出:可写大小为“int current_size*1”字节,但可能写入“2”字节 - Error: C6386: Buffer overrun while writing to 'newArr': the writable size is 'int current_size*1' bytes, but '2' bytes might be written 重新增长数组时出错:写入时缓冲区溢出 - Error while regrowing an array: Buffer overrun while writing to 错误:写入数组时缓冲区溢出。 如何计算以某个字母开头的单词 - Error: buffer overrun while writing to array. How to cout the word which starts with certain letter Placement new是写入比数组大小更多的字节 - Placement new is writing more bytes than array size 在 C++ 代码部分,可能会写入两个字节 - in C++ code section, two bytes might be written std :: array-&#39;大小为n的缓冲区将被溢出&#39;,仅在VS中 - std::array - 'buffer of size n will be overrun', only in VS 有什么方法可以检查在 C 的缓冲区中写入了多少数据/字节 - Is there any way to check how much data/bytes is written in buffer in C 将 size_t 字节写入二进制文件 - Writing bytes of size_t to binary file 当字节以偏移量0写入文件时,能否保持写入时间稳定? - Is it possible to keep writing time stable when bytes are written at offset 0 on a file? 将struct写入文件时,写入了太多字节 - When writing struct to a file too many bytes are written
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM