Segmentation fault- strcat

You don’t have enough space in fn. By strcat’ing on to it you overwrite the end of its stack allocation and into the stack .. hence the segmentation fault.

You could try the following instead:

char fn[255];
strcpy( fn, "~/lyrics/" );
strcat( fn, argv[1] );
strcat( fn, ".txt" );

You just have to be sure that the whole path and filename can fit into 255 characters.

Alternatively you could do this:

char* fn = NULL;
int argvLen = strlen( argv[1] );
fn = malloc( 9 + argvLen + 4 + 1 ); // Add 1 for null terminator.
strcpy( fn, "~/lyrics/" );
strcat( fn, argv[1] );
strcat( fn, ".txt" );

And you have definitely allocated enough space for the string. Just don’t forget to free it when you have finished with it!

Leave a Comment