I'm new to C so forgive me if this is too obvious, but I am having an issue finding the error in my code that is leading to a segmentation fault. I believe the issue may be in the usage of malloc(), but I am not positive.
Here is the code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX_STRING 20
char* getFirstName (char* firstName
)
{
char* myfirstName = (char*)malloc(strlen(firstName)+1);
printf("Please enter your first name: ");
fgets(firstName,MAX_STRING,stdin);
return(myfirstName);
}
char* getLastName (char* lastName
)
{
char* mylastName = (char*)malloc(strlen(lastName)+1);
printf("Please enter your last name: ");
fgets(lastName,MAX_STRING,stdin);
return(mylastName);
}
char* getNickName (char* nickName
)
{
char* mynickName = (char*)malloc(strlen(nickName)+1);
printf("Please enter your nick name: ");
fgets(nickName,MAX_STRING,stdin);
return(mynickName);
}
char* getCompleteName (const char* firstName,
const char* lastName,
const char* nickName,
char* completeName
)
{
snprintf(completeName,MAX_STRING,"%s \"%s\" %s",firstName,nickName,lastName);
}
int main ()
{
char* firstName;
char* lastName;
char* nickName;
char* completeName;
firstName = getFirstName(firstName);
lastName = getLastName(lastName);
nickName = getNickName(nickName);
completeName = getCompleteName(firstName,lastName,nickName,completeName);
printf("Hello %s.\n",completeName);
free(firstName);
free(lastName);
free(nickName);
return(EXIT_SUCCESS);
}
Does it seem that I am using malloc() in the correct way?