-1

I wanted to make a double array where the size will depends of the value enter by the user but when my double array is around [1999] I got segmentation fault.

So I decided to use pointers but here the problem, I set my value at 0 but after a few loop iterations, my value would change by itself.

Here is my code:

int Limit = 0;
int Bomb = 0;  

int getsum(int num)
{
    int result = 0;
    while (num)
    {
        result = result + num % 10;
        num /= 10;
    }
    return result;
}

int calc_limit(int x)
{
    while ((getsum(x)) < Bomb)
        x++;

    return x;
}

int main(int argc, char **argv)
{
    Bomb = atoi(argv[1]);
    Limit = calc_limit(0);
    int i = 0;
    int j = 0;
    bool **visited;                                                                                     

    if ((visited = malloc(Limit * sizeof(bool))) == NULL)
        return;
    while (i < Limit)
    {
        if ((visited[i] = malloc(Limit)) == NULL)
            return;
        while (j < Limit)
        {
            visited[i][j] = false;
            j++;
        }
        j = 0;
        i++;
    }
    //  printf("%d\n", visited[0][0]);                                                                                 
}

So for example, visited[0][0], is equal 0 when I set it but suddenly it will became equal 176.

I checked when this value change, and it change it change in my second loop when i = 3.

I have no idea why.

Thanks for your help

WedaPashi
  • 3,561
  • 26
  • 42
Thebeginner
  • 143
  • 3
  • 15

1 Answers1

1

One problem is that you don't allocate enough memory for visited.

if ((visited = malloc(Limit * sizeof(bool))) == NULL)

should be:

if ((visited = malloc(Limit * sizeof (bool*))) == NULL)

or:

if ((visited = malloc(Limit * sizeof *visited)) == NULL)

Note that sizeof is an operator and not a function. Therefore most code styleguides recommend a space between sizeof and its parameter.

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • That was the reason, thanks. I'm curious why it did this exactly – Thebeginner Jan 25 '18 at 09:54
  • @Thebeginner Compare the value you get for `sizeof (bool)` with `sizeof (bool*)`. You will see that the former is smaller than the latter on your platform. My guess is that you get the values `1` and `8` or perhaps `1` and `4`. – Klas Lindbäck Jan 25 '18 at 11:30
  • 1
    Also `visited[i] = malloc(Limit)` should be `visited[i] = malloc(Limit * sizeof *visited[i])` – M.M Jan 25 '18 at 13:09