For this assignment I'm supposed to grab multiple names from the command line arguments which are prefaced with either '+' (which inserts the name into my linked list) or '-' (which removes the name from the list), so if I were to enter "+bill +jim +ted -bill", I would add those three names without the '+' and remove bill. Ive tried to dynamically allocate a string using malloc
so I can modify the name
string, but my code doesnt insert the string data into my linked list, and I get a free(): invalid pointer error when I pass through some test strings. If I move the free(name)
statement to the if/else if statements I get a segmentation fault. How would I go about dynamically allocating these strings from the command line correctly so they can be modified?
int main(int argc, char *argv[]){
struct node* head;
for(int x = 0; x < argc; x++){
char * name = malloc((strlen(argv[x])+1));
name = argv[x];
if(name[0] == '+'){
printf("adding %s \n", name++);
insert(&head, name++);
printf("List: ");
printList(&head);
}
else if(name[0] == '-'){
printf("removing %s \n", name++);
removeNode(&head, name++);
}
free(name);
}
}
char * removeNode(struct node** head, char* name){
struct node *current = *head;
struct node *previous;
if(current == NULL){
return "error0";
}
if(current->data == name){
struct node * node2delete= *head;
*head = node2delete->next;
char * name2 = malloc(strlen(name)+1);
strcpy(name2, name);
free(node2delete);
printf("Removed %s \n", name);
return name2;
}
while(current != NULL){
previous = current;
current = current->next;
if(current->data == name){
previous->next = current->next;
char * name2 = malloc(strlen(name)+1);
strcpy(name2, name);
free(current);
printf("Removed %s \n", name);
return name2;
}
}
return "error0";
}