Gian
Gian

Reputation: 357

Problems when dynamically allocating a matrix in memory

I'm sorry if the title isn't specific enough on the issue, but I'm having some really weird and inconsistent problems with double pointers and I don't know how to describe them in just a sentence.

Basically, every time my program runs it allocates a matrix which size's is randomly generated on the fly.

coord mapSize;

mapSize.row = randomRange(3, 5);
mapSize.column = randomRange(5, 7);

char** map = (char**) malloc (mapSize.row * sizeof(char));

for (int i = 0; i < mapSize.row; i++) 
{
    map[i] = (char*) malloc (mapSize.column * sizeof(char));
}

Then the matrix gets initialized:

for (int i = 0; i < mapSize.row; i++)
{
    for (int j = 0; j < mapSize.column; j++)
    {
        map[i][j] = CLEAN_FLOOR_SYMBOL;
    }
}

This works perfectly as long as the matrix doesn't exceed 4 rows in size. If that happens, the program just crashes when initialitation gets to the fifth row. What's weirder is that even if the number of rows is higher than 5, the problem still arises when initialitation gets to the fifth row.

I've verified this by printing off some values during the initialitation loops.

printf("r: %d c: %d\n\n", mapSize.row, mapSize.column);

for (int i = 0; i < mapSize.row; i++)
{
    printf("r: %d | c: ", i);
    for (int j = 0; j < mapSize.column; j++)
    {
        map[i][j] = CLEAN_FLOOR_SYMBOL;
        printf("%d ", j);
    }
    printf("\n");
}

error

Here there were 6 rows, but the program still crashed when trying to initialise the fifth.

What's even weirder is that none of these problems seem to arise when running the program on eclipse's console. So, how and am I messing up?

Upvotes: 0

Views: 79

Answers (1)

Swordfish
Swordfish

Reputation: 13134

In

char** map = (char**) malloc (mapSize.row * sizeof(char));

you're missing a *, and please don't cast the result of *alloc()*):

char **map = malloc (mapSize.row * sizeof(char*));
//                                            ^
//                                           here

Better:

char **map = malloc (mapSize.row * sizeof(*map));

as here the type the size is taken of changes with the type of map so you don't have to remember to change the type in multiple places if it should ever change.

If you want performance though, get rid of the **. Look up what a jagged array is and avoid it:

size_t num_rows = // ...
size_t num_cols = // ...
char *foo = malloc(num_rows * num_cols * sizeof *foo);

// access:
size_t row = // ...
size_t col = // ...
foo[row * num_rows + col];


*) If your compiler complains you are using a C++-compiler to compile C code.

Upvotes: 2

Related Questions