0

Here is my code:

Class Header file:

#pragma once

class dyn_array 
{

    int totalSize;
    int numberOfElements;
    int* data;

public:

    dyn_array();

    dyn_array(const dyn_array&);

};

Class cpp file:

#include<iostream>
#include "dyn_array.h"

using namespace std;

dyn_array::dyn_array()
{

    totalSize = 4;
    numberOfElements = 0;
    data = new int[totalSize];

}

dyn_array::dyn_array(const dyn_array& copy)  
{
    totalSize = copy.totalSize;
    numberOfElements = copy.numberOfElements;
    data = new int[copy.totalSize];

    for (int i = 0; i < numberOfElements; i++)
        data[i] = copy.data[i];              //this line showing error
}

The compiler is showing me the following error:

Buffer overrun while writing to 'data': the writable size is 'copy.totalSize*4' bytes, 
but '8' bytes might be written.

I am new to Object Oriented Programming, please explain me the error, and how can I correct it?

Rehab
  • 45
  • 5
  • 2
    What is the value of `copy.totalSize` and `copy.numberOfElements` when the error occurs? – Daniel Langr May 17 '20 at 11:21
  • 1
    I think it would be save to check if(numberOfElements <= totalSize). Once numberOfElements is > totalSize you will get a memory leak. Which compiler du you use? – andrew28349 May 17 '20 at 11:27
  • In the actual code i have added those options... I am using visual studio. The error is showing without calling the copy constructor. – Rehab May 17 '20 at 11:36
  • You should adhere to the rule of 3. You have a copy constructor, so you must also write a destructor (to avoid a memory leak), and assignment operator (to avoid double-free and memory corruption, and more...). Most likely some code invoked the default operator= – Michael Veksler May 17 '20 at 11:39
  • @andrew28349 This is a perfect case for `assert` instead of `if`, since such a situation should not be caused by usage of the class. If it happens, it's a mistake of class writer. Also, there is no memory leak, there is buffer overflow (accessing data beyond the allocated range). – Daniel Langr May 17 '20 at 11:56
  • If the error is showing even without calling copy constructor, and it points out to the code of the copy constructor, it may be a problem with the diagnostic tool. But then, where would that 8 stem from? Is it hard-error (which prevents building the program), or only a warning? – Daniel Langr May 17 '20 at 11:58
  • Thank you, I have a destructor in the actual program. I will look up the assignment operator. – Rehab May 17 '20 at 12:00
  • It's only warning @DanielLangr – Rehab May 17 '20 at 12:01
  • @Rehab Then, these questions may be relevant, as well as others (use Google with the error message): [VS2015: C6386 Buffer Overrun while writing (even for same index value)](https://stackoverflow.com/q/37205179/580083), [Visual Studio 2015 Code Analysis C6386 warns of buffer overrun](https://stackoverflow.com/q/41943803/580083). – Daniel Langr May 17 '20 at 12:52

0 Answers0