Search code examples
cstrcmp

segmentation fault with strcmp?


I am trying to understand why my code crashes. I have an array of structs which look like this:

typedef struct contact {

    char cFirstName[10];
    char cLastName[10];
    char cTelphone[12];

} address ; // end type

In the code I initialize the array like this:

address myContacts[5];

for ( i = 0; i < 5 ; i++ ){
        strcpy(myContacts[i].cFirstName, "0");
        strcpy(myContacts[i].cLastName,"0");
        strcpy(myContacts[i].cTelphone,"0"); 
    }

This works:

for ( i = 0; strcmp(myContacts[i].cFirstName,"0") != 0 ; i++ ){                                             
        printf("\nmyContacts[%d].cFirstName: %s", i, \
        myContacts[i].cFirstName );
    }// end for

So, I only print out Contacts which have content.

However, I can't under stand why my search contact function does not work:

void searchContact( address * myContacts,    char * name ){
    int found = 1;
    int i = 0;

    for ( i = 1; found != 0 ;i++ ){
    found=strcmp(myContacts[i-1].cFirstName, name);

    printf(" Name Found %s",   myContacts[i-1].cFirstName);
    }
} // end of searchContacts

I call this function like this:

printf("\nEnter a name or part of a name to search:\n");
            fscanf(stdin, "%s", buffer);
            getchar(); // clear the last enter
            printf("\nThe line you entered was:\n");
            printf("%s\n", buffer);
            searchContact( myContacts, buffer );

If I search for an existing name it is found, and everything is OK. However, searching for a non existing name, causes a segmentation fault. Is there an obvious thing I am missing here ?


Solution

  • The probelm is here:

            for ( i = 1; found != 0 ;i++ ){
            found=strcmp(myContacts[i-1].cFirstName, name);
    
            printf(" Name Found %s",   myContacts[i-1].cFirstName);
            }
    

    You need to add something like for ( i = 1; found != 0 && i < num_of_contacts ;i++ ) otherwise you going out of your array!