Austin Leigh
Austin Leigh

Reputation: 31

segfault at strcmp - possibly issue passing pointer from struct

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 :)

Upvotes: 2

Views: 275

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74395

Besides using uninitialised memory in srch, you have no condition to stop the loop at the end of the list. You should modify it to something like this:

while (cur != NULL && strcmp(cur->name, srch) != 0){
   cur = cur->next;
}

Otherwise at the end of the list, cur would become NULL and null pointer dereference would occur at cur->name on the next iteration.

Upvotes: 1

Olaf Dietsche
Olaf Dietsche

Reputation: 74048

In the line

srchbuff[i] = '\0';

you write one byte beyond the end of srchbuff.

The memory srch points to, is not initialized. So anything might happen.

cur is also not initialized. This means cur points anywhere and so does cur->name.

Upvotes: 6

Related Questions