开发者

Why do I get a seg fault? I want to put a char array pointer inside a struct

开发者 https://www.devze.com 2023-04-10 15:45 出处:网络
consider the fallowing code: typedef struct port * pport; struct port { int a; int b; pport next; pport prev;

consider the fallowing code:

typedef struct port * pport;

struct port
{
  int a;
  int b;
  pport next;
  pport prev;
  char * port;
};

void addNewport(pport head)
{
  pport 开发者_高级运维newPort = (pport)malloc(sizeof(pport*));
  newPort->prev=temp;
  head->next=newPort;
}

int main()
{
  pport head = (pport)malloc(sizeof(pport*));
  addNewport(head);
}

This will result in seg fault if try to add a new port via a subroutine, but if I perform it the main, no seg fault will appear. Why is that?


Replace

 malloc(sizeof(pport*))

with

 malloc(sizeof(struct port))

because you don't want to allocate memory for a pointer, rather for the struct.

0

精彩评论

暂无评论...
验证码 换一张
取 消