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

百般思念 提交于 2019-12-12 05:48:14

问题


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?


回答1:


Replace

 malloc(sizeof(pport*))

with

 malloc(sizeof(struct port))

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



来源:https://stackoverflow.com/questions/7623994/why-do-i-get-a-seg-fault-i-want-to-put-a-char-array-pointer-inside-a-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!