当我更改与之相关的结构时,内存分配不起作用
我目前正在使用一个结构
struct Player{
Object obj;
int touched;
};
typedef struct Player *Player;
,这是该结构中元素的创建:
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;
}
这样的每个编译都完美。 但是,如果我的结构中有2个元素,
struct Player{
Object obj;
int touched;
int frequency;
int lastTouch;
};
typedef struct Player *Player;
我会在执行中收到此错误消息(代码完美地编译):
malloc():无效的大小(UNSORTED) 中止(核心倾倒)
我不明白为什么会收到此错误消息,因为我还没有使用这两个新变量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能应该按原样定义
player
将其定义。 Like this:Then do this:
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:or
Instead of defining
Player
as a pointer, you should probably define it as is. Like this:Then do this:
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:or
在线上,
您仅在为整个结构分配时仅为指针分配。
您应该做:
添加
*
以放置指针并获取结构类型。不建议使用
typedef
掩盖typedef struct player *player;
之类的指针,因为它可能会引起这种混乱。At the line
you are allocating only for a pointer while allocating for the whole structure is required.
You should do:
Add
*
to dereference the pointer and get the structure type.Using
typedef
to obscure pointers liketypedef struct Player *Player;
is not recommended because it can cause this type of confusion.