Question

I'm building a class and at some point I call a delete. In codeblocks it works and in Visual Studio 2013 it doesn't.

In my class I have:

    private:
    bool sign;          // 0 if positive, 1 if negative
    int NumberSize;
    int VectorSize;
    int *Number;

Then I have this function:

  void XXLint::Edit(const char* s)
{
// Get Size
this->NumberSize = strlen(s);

// Initialise Sign
if (s[0] == '-')
{
    this->sign = 1;
    s++;
}
else if (s[0] == '+') s++;
else this->sign = 0;

delete[] Number;  // Here the debugger gives me the error

//Get Vector Size

this->VectorSize = this->NumberSize / 4;

// Allocate Memory
this->Number = new int[this->VectorSize];

//Store the string into the number vector.

int location = this->VectorSize;
int current = this->NumberSize - 1;

while (location)
{
    int aux = 0;
    for (int i = 3; i >= 0 && current; i--)
    if (current - i >= 0)
        aux = aux * 10 + s[current - i] - '0';
    current -= 4;
    this->Number[location--] = aux;
}

} I did read the article and it really is interesting :D but i don't belive that's where the error comes from. Why is this error happening?

Was it helpful?

Solution

Look here:

this->Number = new int[this->VectorSize];
int location = this->VectorSize;

Assume for argument's sake that this->VectorSize == 10. So location now has the value 10. However, later you do this in a loop:

while (location)
{
   //...
   this->Number[location--] = aux;  // out of bounds!
}

You are accessing this->Number[10]. That is a memory overwrite. And no, location doesn't get decremented before it's used, as it is post-decrement, not pre-decrement.

When you compile a program on another compiler and then run the program, if that runtime detects errors, always question your code. It doesn't matter if it "worked" on compiler X, or if it worked on your computer and your friend's computer but not the teacher or customer's computer. Always suspect there is something wrong with your code if there is a failure such as memory corruption.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top