0

Why does this show a warning for dereferencing nullptr in C

Level1Tilemap->Map = (int*)((malloc(Level1Columns * sizeof(int))));

for (int i = 0; i < Level1Columns; i++)
{
    Level1Tilemap->Map[i] = malloc(Level1Rows * sizeof(int));

    for (int j = 0; j < Level1Rows; j++)
    {
        Level1Tilemap->Map[i][j] = Level1MapStaticArray[i][j];
    }
}

I am using malloc to create a 2D array of ints

But the editor shows warning and Level1Tilemap->Map has the memory address of nullptr

And the defination int** Map;

5
  • 2
    At a guess your editor is simply warning you that malloc can return a null pointer and you should check for that Commented Mar 15, 2022 at 11:38
  • 2
    In the first allocation, you use sizeof(int) but you probably want sizeof(int*) Commented Mar 15, 2022 at 11:39
  • 1
    Probably not your issue, but you want (int*)((malloc(Level1Columns * sizeof(int)))); -> (int*)((malloc(Level1Columns * sizeof(int*)))); Commented Mar 15, 2022 at 11:39
  • 1
    Check for malloc returning NULL, and if it does, use perror() to print it. Commented Mar 15, 2022 at 11:39
  • 1
    Is your Level1Tilemap properly set to something? And is it Level1Tilemap->Map = (int**)malloc... you want? Commented Mar 15, 2022 at 11:46

2 Answers 2

2

You might have meant to use a pointer-to-pointer, in which case sizeof(int) should have been sizeof(int*). However, don't do that, it's obscure and slow, for no good reason.

Instead do

size_t size = sizeof(int[Level1Columns][Level1Rows]);

int (*something)[Level1Rows] = malloc(size);
if(something == NULL) { /* error handling */ }

memcpy(something, Level1MapStaticArray, size);
...
free(something);

Apart from reducing code complexity, this will significantly outperform the code you have currently.

Sign up to request clarification or add additional context in comments.

Comments

-1
// map is an array of (int*), and the length is column
int** map = (int**) malloc(column * sizeof(int*));

for (int i = 0; i < column; ++i) {
    // map[i] is an array of int, and the length is row
    map[i] = malloc(row * sizeof(int*));

    for (int j = 0; j < row; ++j)
        map[i][j] = 0;
}

2 Comments

You fixed the first malloc call and broke the second one instead...
Anyway, there is no sensible reason why you would ever want to use a fragmented malloc like this, when dealing with a plain 2D int array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.