std::bad_alloc at memory location (probably sth with creating dynamic tables)

982 views Asked by At

I've got problem creating a dynamic table in c++. My program breaks and shouts:

Unhandled exception at at 0x75914598 in xxx.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0107F73C.

I know there is something I'm missing so if could you be so kind and point me where and how to repair it. The ll has random value, (but even if I set a value like in code underneath I'm getting same error, so the problem is with following code), which is ganerated in another function (problem is with this code :/).

Full code: http://pastebin.com/Gafjd5Um

Code:

#include <iostream>
#include <math.h>
#include <cstdio>
#include <locale.h>
#include <conio.h>
#include <cstdlib>
#include <time.h> 
#include <vector>

class GeneratePass
{

private:
    //int length;
    int ll=5; 
    char *lowertab;

public:
    void ChooseLenght();
    void CreateList();
    GeneratePass()
    {
        lowertab = new char[ll];
    }
    ~GeneratePass() 
    { 
        delete[] lowertab; 
    }
};

void GeneratePass::CreateList()
{


    srand( time( NULL ) );
    int i, j;

    for( i = 0; i < ll; i++ )
    {
        lowertab[ i ] =( char )( rand() % 24 ) + 97;

    }
    for( i = 0; i < ll; i++ )
    {
        cout << lowertab[ i ];

    }
}


int main()
{
GeneratePass create;
create.CreateList();

return 0;
}
2

There are 2 answers

2
Tim3880 On BEST ANSWER

Your full code failed in "creating " the two objects.

In your full code, you didn't initialize the ll but you used it in the constructor. If you intend to let the user choose the length, you should NOT create the array in your constructor. Instead you need do it in the choose_length function.

  GeneratePass()
  {
    lowertab = NULL;
    ll=0;
  }


 void GeneratePass::CreateList()
 {
     if(ll<1 || ll > 1024*1024*1024) throw "Invalid length";
     lowertab = new char[ll];
     ....
     <your code here>

 }
7
Daniel Jour On

Looking at your full code:

In lines 162 and 163 you construct two distinct instances of your GeneratePass class. In the following lines 167 and 168 you call ChooseLength on one object and createList on the other.

Since the objects do not share any information, the member field ll of the object create is uninitialised, and could therefore be some extremely large value.

In consequence, the allocation fails and throws std::bad_alloc.

To fix this you need to use just one object.