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);
}
}
CodePudding user response:
Try using strcpy(name, argv[x]);
instead of name = argv[x]
, because when you assign a pointer to a pointer, they will lead to the same memory location where your null-terminated char array is stored. So that you could've done a memory deallocation for the argv[x] when you called free(name);
The pointer opperations are not the same as value assignments.
also see this thread: How do malloc() and free() work?
CodePudding user response:
Many problems
Incorrect copying of string
//char * name = malloc((strlen(argv[x]) 1));
//name = argv[x];
char * name = malloc(strlen(argv[x]) 1);
if (name == NULL) return EXIT_FAILURE; // Out of memory
strcpy(name, argv[x]);
Incorrect free()
Code needs to free the same value received from allocation. name
messes that up.
Uninitialized head*
// struct node* head;
struct node* head == NULL;
More
Likely only need to allocate when adding and allocated after the /-
.
int main(int argc, char *argv[]){
struct node* head = NULL;
// for(int x = 0; x < argc; x ){
for(int x = 1; x < argc; x ){ // Skip adding the program name, start at 1
if(argv[x][0] == ' '){
char * name = malloc((strlen(argv[x] 1) 1));
if (name == NULL) return EXIT_FAILURE; // Out of memory
strcpy(name, argv[x]);
printf("adding %s \n", name); // No
insert(&head, name); // No
printf("List: ");
printList(&head);
}
else if(argv[x][0] == '-'){
printf("removing %s \n", argv[x] 1);
// This is a problem, I'd expect removeNode() to return a pointer to the free'd name
char *name = removeNode(&head, argv[x] 1);
free(name);
}
}