Home > OS >  HEAP CORRPUTION DETECTED: after Normal block (#187)
HEAP CORRPUTION DETECTED: after Normal block (#187)

Time:07-20

Wrote a simple program. You write a number in the console and an array with the size of the number you wrote in is created and printed. I have now this error, heap corruption detected and I see no problems with my code so please help me out.

#include <iostream>

class dmas
{
public:
    int num;
    dmas(int size)
    {
        this->num = size;
    }
    int* a = new int[num];
    void logic()
    {
        for (int i = 0; i < num; i  )
        {
            a[i] = rand() % 100;
        }
    }

    void print()
    {
            for (int i = 0; i < num; i  )
            {
                std::cout << a[i] << std::endl;
            }
            delete [] a;
    }
};

int main()
{
    srand(time(NULL));
    int size;
    std::cout << "Enter the size of the massive" << std::endl;
    std::cin >> size;
    dmas a(size);
    a.logic();
    a.print();
    return 0;
}

CodePudding user response:

The problem is this initialization of the pointer a

class dmas
{
public:
    int num;
    dmas(int size)
    {
        this->num = size;
    }
    int* a = new int[num];
    //...

The call of the operator new occurs when the variable num is default initialized and has no yet the value of the parameter size assigned to it in the body of the constructor.

At least you need to write

    dmas(int size) : num( size )
    {
    }

Pay attention to that the call of operator delete []

delete [] a;

you should move from the function print to the class destructor.

CodePudding user response:

Let's check the value of num at the allocation.

I added a function

int printNum(int num) {
    std::cout << "num = " << num << std::endl;
    return num;
}

and changed the allocation

    int* a = new int[num];

to

    int* a = new int[printNum(num)];

This resulted in num = 0 being printed despite of I entered 10 for the standard input.

Now you can see the value of num set in the constructor is not used here.

To fix this, you can use member initializer:

    dmas(int size) : num(size)
    {
    }

CodePudding user response:

You don't allocate any memory at all, because this int* a = new int[num]; is outside the scope of your constructor!

To make it work, replace this piece of code:

public:
    int num;
    dmas(int size)
    {
        this->num = size;
    }
    int* a = new int[num];

with this:

public:
    int num;
    int *a;
    dmas(int size)
    {
        this->num = size;
        a = new int[num];
    }

Then should work fine!

  • Related