0

Below is the code. When I'm trying to debug this program, I get information:

Unhandled exception at 0x009E1BBC in MES1.exe: 0xC0000005: Access violation reading location 0xCCCCCCCC.

Debugger underlined this line:

function.tab[0][0] = 4;

Source.cpp:

#include <iostream>
#include <conio.h>
#include "Function.h"
using namespace std;

int main()
{
    Function function;
    function.k = 4;
    function.tab[0][0] = 4;
    cout << function.k;
    system("pause");
    return 0;
}

Function.cpp:

#include "Function.h"

void Function::Allocate(float **tab, float*tabW)
{
    tab = new float *[3];
    for (int i = 0; i < 3; ++i)
    {
        tab[i] = new float[3];
    }
    tabW = new float[4];
}

Function::Function()
{
    k = 50;
    alfa = 10;
    S = 2;
    L = 5;
    L1 = 2.5;
    L2 = 2.5;
    q = -150;
    t = 400;

    Allocate(&*tab,&*tabW);
}

Function::~Function()
{
    delete[] tab;
    tab = nullptr;
}

Function.h:

#ifndef Function_h
#define Function_h

class Function
{
public:
    float** tab;
    float* tabW;
    float k;
    float alfa;
    float S;
    float L;
    float L1;
    float L2;
    float q;
    float t;

    float t1;
    float t2;
    float t3;

    float C;

    Function();
    ~Function();
    void Allocate(float **tab, float*tabW);
};

#endif
Plusce
  • 117
  • 2
  • 14
  • 1
    0xCCCCCCCC = uninitialized stack memory. http://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations/127404#127404 – drescherjm Nov 03 '16 at 19:22
  • You really should be using a `std::vector` if you want a dynamic sized array that can grow. – NathanOliver Nov 03 '16 at 19:23
  • 4
    Why does `Allocate` take those arguments? You're assigning to the arguments instead of the instance variables there. – user2357112 Nov 03 '16 at 19:24
  • Also, that destructor isn't deleting everything it needs to. – user2357112 Nov 03 '16 at 19:25
  • Ok. thank you. So how shall I change the "Allocate" arguments? I also edited delete function in this way: `delete[] tab[0]; delete[] tab[1]; delete[] tab[2]; delete[] tab;` – Plusce Nov 03 '16 at 19:30
  • 1
    ***So how shall I change the "Allocate" arguments?*** Remove the arguments completely and your problem should be fixed. Your arguments are masking the member variables of the same name. – drescherjm Nov 03 '16 at 19:32
  • Great, now everything is ok. Thank you. Also I would like to ask: is my delete function ok now? – Plusce Nov 03 '16 at 19:41
  • 1
    Everything you `new`, you must `delete`, so if you have `new` in a `for` loop, I'd expect `delete` in a `for` loop to clean up. – user4581301 Nov 03 '16 at 20:05

0 Answers0