0

Hello I am working on a game written in C with SDL2. I have created a player struct, which has a pointer to an SDL_Rect. But it seems that the value of the rect is being overwritten, which you can see in the screenshot.

Console of the game, first two logs are the values which it should contain

Here is the Player struct:

struct Player* createPlayer(int x, int y, int width, int height, SDL_Texture* texture) {
  struct Player* player = (struct Player*) malloc(sizeof(struct Player));
  SDL_Rect rect = {x, y, width, height};

  player->rect = ▭
  player->texture = texture;
  printf("%d\n", player->rect->x);
  return player;
}

Here is the main function:

struct Player* player = createPlayer(0, 0, 128, 128, texture);
bool running = true;
printf("%d\n", player->rect->x);
while(running) {
  SDL_Event event;

  // UPDATE PLAYERS AND STUFF HERE

  while(SDL_PollEvent(&event)) {
    switch(event.type) {
      case SDL_QUIT:
        running = false;

        break;
    }
  }

  SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
  SDL_RenderClear(renderer);

  // RENDER PLAYERS AND STUFF HERE
  printf("%d\n", player->rect->x); <- This is where the different values come from
  SDL_RenderCopy(renderer, player->texture, NULL, player->rect);

  //

  SDL_RenderPresent(renderer);
}
leonphil
  • 15
  • 1
  • 4

1 Answers1

1

You are assigning the pointer to a local variable:

  SDL_Rect rect = {x, y, width, height};

  player->rect = &rect;

The local variable will be invalid once it goes out of scope (when reaching the end of the function), and any pointer to it will point to invalid memory -> undefined behaviour.

Write ...

  SDL_Rect rect = {x, y, width, height};

  player->rect = malloc(sizeof(SDL_Rect);
  *player->rect = rect;
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58