I am attempting to compare a user inputted search term with a number of names in a linked list. I know for sure that it is segfaulting at strcmp but none of the solutions for segfaults at strcmp seem to be the problem.
Here is my code! I am still very new to StackOverflow & C so I apologize in advance for any dumb mistakes I make in the posting of this or in my actual programming. ><
struct node{
char* name;
struct node* next;
};
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char reader;
char srchbuff[1001];
char name[10] = "Justin";
char* srch;
int i;
struct node *head;
struct node *cur;
head = malloc(sizeof(struct node));
head->name = name;
head->next = 0;
for(i=0; i<1000; i++){
scanf("%c", &reader);
srchbuff[i] = reader;
}
srchbuff[i] = '\0';
srch = malloc(sizeof(char)*i);
strcpy(srch, srchbuff);
cur = head;
while( (cur != NULL) && (strcmp(cur->name, srch)) != 0){
cur = cur->next;
}
}
There are other nodes allocated in a separate function, that works fine, and the information is also allocated in a separate function (it also works fine), and my struct is in my header file so it’s all happy and recognized.
I have also tested with gdb and printf statements to make sure the strcmp is where I’m segfaulting, and it definitely is. Thanks in advance for any suggestions 🙂
In the line
you write one byte beyond the end of srchbuff.
The memory
srchpoints to, is not initialized. So anything might happen.curis also not initialized. This meanscurpoints anywhere and so doescur->name.