Marcus Mardis Marcus Mardis - 1 year ago 85
C Question

C initials program returned "Segmentation fault"

I am working on a initials project where you enter a name and it prints the initials. When I try and combine the strings it returns

Segmentation fault
instead of the initials.

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>

int main(void) {
printf("Name: ");
string name = GetString();

int length = strlen(name);
string initials = "";
int arraylength = length + 1;
char string[arraylength];
string[0] = toupper(name[0]);
int count = 1;
for(int l = 1;l<=length;l++) {
if(name[l] == ' ') {
string[l] = toupper(name[l]);
string[count] = '\0';
for(int c = 0;c<=count;c++) {
strcat(initials, &string[c]);
printf("%s\n", initials);

Answer Source

That's why a string type would cause confusion, you make a pointer to a single char. And you then pass it to strcat() that's simply wrong.

A string, as expected by strlen() or strcat() or all str* functions, is not simple a char pointer which is what the type string in your code is.

In a is actually a sequence of bytes with the last byte being '\0', and it's not optional. You create a pointer to a single char and that is not the same as a string that I just described.

Any of the str* functions will try to find the '\0' but since you passed the address of a stack variable which is not an array, the behavior is undefined when any of these functions try to increment and dereference the passed pointer.

When you do understand how strings work in you would see that using strcat() for the concatenation of many chunks of a large string together is not very efficient, you would also know that you just need to append a single char and that you can by simply using index notation, like

char string[8];

string[0] = 'E';
string[1] = 'x';
string[2] = 'a';
string[3] = 'm';
string[4] = 'p';
string[5] = 'l';
string[6] = 'e';
string[7] = '\0'; // The very necessary terminator
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download