Crash on calloc()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    int** vlocky;
    vlocky = (int**) calloc (pocVlociek,sizeof(bool*));
    for(int i = 0; i<pocVlociek; i++)
    vlocky[i] = (int*) calloc (6,sizeof(bool));

    for(int i = 0; i<pocVlociek; i++)
        for(int j = 0; j<6; j++)
            fscanf(input,"%d",&vlocky[i][j]);

    bool** hashtable;
    hashtable = (bool**)calloc(pocVlociek,sizeof(bool*)); // This line
    for(int i = 0; i<pocVlociek; i++)
    hashtable[i] = (bool*) calloc (pocVlociek,sizeof(bool));

    for(int i = 0;i<pocVlociek;i++)
        for(int j = 0; j<pocVlociek;j++)
        hashtable[i][j] = false;

This is piece of some code Im writing, however Im don't have much expierience with dynamic memory allocation. There are 2 2D array allocations in this code and for some reason it crashes when hashtable is about to get allocated.
Can someone please explain to me why is it happening and how to make it work? It cannot be because of lack of memory because 'pocVlociek', an integer that basicly sets how large will allocation be ranges only from 2 to 5. Thanks
how large will allocation be ranges only from 2 to 5
Then I suggest to use static allocated arrays, and just keep track of the used space. Or use an STL container, like std::vector
1
2
int vlocky[5][6];
bool hashtable[5][5];


¿Is this c++ or are you using a macro to define the bool type?
1
2
3
4
for(int i = 0; i<pocVlociek; i++)
    vlocky[i] = (int*) calloc (6,sizeof(bool));
//...
scanf(input,"%d",&vlocky[i][j]);
That is an error as you allocate memory for bool, but you threat it as an integer.
It might be that are not allocating enough memory:
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main()
{
  cout << "Sizeof(bool): " << sizeof(bool) << endl;
  cout << "Sizeof(int): " << sizeof(int) << endl;
  return 0;
}
Sizeof(bool): 1
Sizeof(int): 4

Try changing
1
2
3
4
//Change 
vlocky[i] = (int*) calloc (6,sizeof(bool));
// To
vlocky[i] = (int*) calloc (6,sizeof(int));
Thanks, I can't believe that I put bool there instead of int. I have wasted more than a hour because of typo...
Also I didn't use regular 2D arrays because size of pocVlociek is gonna change when I switch input files. Then it could be caused by lack of memory however input file that Im using now has this variable only this small.
Last edited on
Topic archived. No new replies allowed.