Ronnie Slack
Ronnie Slack

Reputation: 17

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

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?

Upvotes: 0

Views: 80

Answers (1)

slartibartfast
slartibartfast

Reputation: 4438

Replace

 malloc(sizeof(pport*))

with

 malloc(sizeof(struct port))

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

Upvotes: 1

Related Questions