[英]Buffer overrun while writing to 'array': the writable size is '1*4' bytes, but '8' bytes might be written
[英]Error: C6386: Buffer overrun while writing to 'newArr': the writable size is 'int current_size*1' bytes, but '2' bytes might be written
代碼會打印出來。 但它給出了那個錯誤。 目標是將其作為示例打印出來: 4 as:aaaa 8 as:aaaaaaaaa 12 as:aaaaaaaaaaaa 16 as:aaaaaaaaaaaaaaaa
#include<iostream>
using namespace std;
int current_size = 4;
int resize_step = 4;
void add_number(char* &arr, int count, char x){
if(count == current_size){
current_size += resize_step;
char* newArr = new char[current_size];
for(int i=0;i<count;i++) newArr[i] = arr[i];
delete arr;
arr = newArr;
}
arr[count-1] = x;
}
//After
int main(){
char* arr = new char[current_size];
for(int count=0;count<4;count++){
add_number(arr, count+1, '1' + count);
}
for(int i=0;i<4;i++) cout<<arr[i]<<" ";
return 0;
}
所以我重寫了代碼。 但預期的 output 是:預期答案:4 as:aaaa 8 as:aaaaaaaa 12 as:aaaaaaaaaaaa 16 as:aaaaaaaaaaaaaaaa
我只得到第一行4 作為 aaaa
#include <iostream>
using namespace std;
int current_size = 4;
int resize_step = 4;
//This functions add the value x at the last position in the array
//The count of elements is indicated by the variable count
//If the array is already at maximum it resizes
//The array starts at current_size size and resizes in resize_step intervals
void add_number(char*& arr, int count, char x)
{
//Your code starts here
arr = new char[current_size];
for (int i = 0; i < current_size; i++)
{
//arr[i] = x;
if (count >= current_size)
{
current_size += resize_step;
char* array2 = new char[current_size - resize_step];
for (int j = 0; j < sizeof(array2); j++)
{
array2[j] = arr[j];
}
delete[](arr);
arr = array2;
}
arr[i] = x;
}
}
int main() {
char* arr = new char[current_size];
char x = 'a';
int element = 8;
add_number(arr, element, x);
for (int i = 0; i < current_size; i++)
{
cout << arr[i];
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.