If a string is greater than a certain length, I want to truncate it to a certain length, and replace the last 3 characters with a period ("."). What I have right now causes a segmentation fault:
#define NAME_LENGTH 36
name is of type, char*.
if (strlen(name) > NAME_LENGTH){
//we need to truncate the name
printf("NAME IS TOO LONG.. TRUNCATING\n");
char *nCpy = NULL; //the truncated name
strncpy(nCpy, name, NAME_LENGTH); //copy NAME_LENGTH number of characters from name into nCpy
printf("Truncated name, now adding ...\n");
strcat(name, "..."); //append "..." to end of name
printf("... added, now copying to struct\n");
strcpy(record->name, nCpy); //assign our name in our record
printf("NAME IS NOW: %s\n", record->name);
}
Upon running, if a name that is longer than NAME_LENGTH, I get a segmentation fault.
Enter name > jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj
NAME IS TOO LONG.. TRUNCATING
Segmentation fault (core dumped)