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.
精彩评论