c - malloc nulling other variables -


i using following function

int parse_headers(char *str, struct net_header *header) {     char *pch;     struct net_header *h, *temp;      pch = strtok(str, "\n");     header->name = pch;      h = malloc(sizeof(struct net_header));     header->next = h;     while ((pch = strtok(null, "\n")) != null)     {         h->name = pch;          temp = malloc(sizeof(struct net_header));         h->next = temp;         h = temp;     }     return n_success; } 

up until line header->next = h, works planned. however, after line h = malloc(sizeof(struct net_header));, variables pch , str reason turn null (i set breakpoints find this). after line temp = malloc(sizeof(struct net_header));, header turns null. clearly, have kind of memory management issue, can't seem find is. header argument initialized before call function

header = malloc(sizeof(struct net_header)); 

struct net_header declared as

struct net_header {     char *name;     char *content;     struct net_header *next; }; 

i ran xcode's static analyzer, found no issues. have no compiler warnings or errors. running program on mac os x 10.9.

why variables being nullified after call malloc()?

if need keep strtok result have dup it, example strdup

int parse_headers(char *str, struct net_header *header) {     char *pch;     struct net_header *h, *temp;      pch = strtok(str, "\n");     header->name = strdup(pch);      h = malloc(sizeof(struct net_header));     header->next = h;     while ((pch = strtok(null, "\n")) != null)     {         h->name = strdup(pch);          temp = malloc(sizeof(struct net_header));         h->next = temp;         h = temp;     }     return n_success; } 

you need call free somewhere free memory


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -