strcpy Seg Fault

299 Views Asked by At

according to DDD I'm getting a seg fault from strcpy but I can't quite figure out what I'm doing wrong (still quite new to C). Any help would be greatly appreciated, thanks in advance.

int compare_people(PERSON* first, PERSON* second)
{
    char firstName[32];
    char secondName[32];

    strcpy(firstName, first->name);
    strcpy(secondName, second->name);

    int returnVal = strcmp(firstName, secondName);

    return returnVal;
}
2

There are 2 best solutions below

2
On

It seems that either first or second is equal to NULL or first->name or second->name is equal to NULL or has non-zero terminated data that due to using strcpy exceeds 32 characters. The other reason can be is that first->name or second->name has invalid pointer for example a pointer to a local data that is already destroyed.

Insert a check in the function. For example

assert( first != NULL && second != NULL && 
        first->name != NULL && second->name != NULL &&
        strlen( first->name ) < 32 && strlen( second->name ) < 32 );

Or you can split this assert in several separate asserts.

0
On
 just  try that code.

   #include <stdio.h>
   #include <stdlib.h>
   #include <string.h>
   typedef struct{

     char name[25];
     }PERSON;

   int compare_people(PERSON* first, PERSON* second);
   main()
  {
    PERSON *first,*second;
    first=(PERSON *)malloc(sizeof(PERSON));
    printf("Enter the first name\n");
    scanf("%s",first->name);
    second=(PERSON *)malloc(sizeof(PERSON));
    printf("Enter the second name\n");
    scanf("%s",second->name);

    if((compare_people(first,second)) == 0)
       printf("Two names are same \n");
    else
      printf("Two names are different\n");


   }

   int compare_people(PERSON* first, PERSON* second)
   {
    char firstName[32];
    char secondName[32];

    strcpy(firstName, first->name);
    strcpy(secondName, second->name);

    int returnVal = strcmp(firstName, secondName);
    return returnVal

   }

~