Home > front end >  Memory allocation doesn't work when I change the structure related to it
Memory allocation doesn't work when I change the structure related to it

Time:04-10

I'm currently working with a structure

struct Player{
   Object obj;
   int touched;
};
typedef struct Player *Player;

And here's the creation of an element from this structure :

Player createPlayer(int posiX,int posiY){
    Player p;
    p=malloc(sizeof(p));
    p->obj.posi.x=posiX;
    p->obj.posi.y=posiY;
    p->obj.life=100;
    p->touched=0;
    p->obj.damage=5;
    p->obj.friend=true;
    return p;
}

Like this every compile perfectly. But if I had 2 elements in my structure,

struct Player{
   Object obj;
   int touched;
   int frequency;
   int lastTouch;
};
typedef struct Player *Player;

I got this error message at the execution (The code compile perfectly) :

malloc(): invalid size (unsorted) Aborted (core dumped)

I don't understand why I got this error message, because I don't use yet these two new variables.

CodePudding user response:

Instead of defining Player as a pointer, you should probably define it as is. Like this:

struct Player{
   Object obj;
   int touched;
};
typedef struct Player Player_t;

Then do this:

Player_t *createPlayer(int posiX,int posiY){
    Player_t *p = malloc(sizeof(Player_t));
    p->obj.posi.x=posiX;
    p->obj.posi.y=posiY;
    p->obj.life=100;
    p->touched=0;
    p->obj.damage=5;
    p->obj.friend=true;
    return p;
}

As a side note: It is never a good idea to typedef pointers as you can never know if it is a pointer or not from its name or declaration elsewhere. You should at the very least explicitly say that it is a pointer like this:

typedef struct Player *PlayerPtr;

or

typedef struct Player *Player_p;

CodePudding user response:

At the line

p=malloc(sizeof(p));

you are allocating only for a pointer while allocating for the whole structure is required.

You should do:

p=malloc(sizeof *p);

Add * to dereference the pointer and get the structure type.

Using typedef to obscure pointers like typedef struct Player *Player; is not recommended because it can cause this type of confusion.

  • Related