Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Memory Allocation in C not working

Tags:

c

struct

I'm trying to make a game that requires dynamically sized arrays in C but my code isn't working even though identical code works in another one of my programs.

Here are my #includes

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SwinGame.h" //API for graphics, physics etc
#include <math.h>

Here are my typedefs for the relevant structs used:

typedef struct position_data
{
  double x;
  double y;
} position_data;

typedef enum enemy_type_data {CIRCLE, TRIANGLE, SQUARE} enemy_type_data;

typedef struct enemy_data
{
  position_data location;
  enemy_type_data type;
  bitmap bmp;
  double health;
  double speed;
  int path_to;
} enemy_data;

typedef struct enemy_data_array
{
  int size;
  enemy_data *data;
} enemy_data_array;

Here is the function to add an element to the array:

void add_enemy(enemy_data_array *enemies)
{
  enemy_data *new_array;
  enemies->size++;
  new_array = (enemy_data *)realloc(enemies->data, sizeof(enemy_data) * enemies->size);
  if (new_array) //if realloc fails (ie out of memory) it will return null
  {
    enemies->data = new_array;
    // enemies->data[enemies->size - 1] = read_enemy_data();
    printf("Enemy added successfully!\n");
  }
  else
  {
    printf("FAILED. Out of Memory!\n");
    enemies->size--;
  }
}

And here is my function call and variable declaration in the main procedure:

int main()
{
  path_data my_path[41];
  enemy_data_array enemies;
  enemies.size = 0;
  add_enemy(&enemies);
}

Why isn't this working?

like image 525
Andrew Avatar asked Mar 24 '26 11:03

Andrew


1 Answers

You invoked undefined behavior by passing indeterminate value enemies->data in uninitialized variable having automatic storage duration. Initialize it before using add_enemy().

int main()
{
  path_data my_path[41];
  enemy_data_array enemies;
  enemies.size = 0;
  enemies.data = 0; /* add this line */
  add_enemy(&enemies);
}

0 is a null pointer constant and can safely be converted to pointer NULL. Unlike NULL, 0 will work without including any headers. Of course you can use enemies.data = NULL; with proper header included.

like image 64
MikeCAT Avatar answered Mar 27 '26 01:03

MikeCAT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!