Segmentation fault- strcat

倖福魔咒の 提交于 2019-12-06 03:48:11

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!

char *fn = "~/lyrics/";

Because fn could point on a string in read-only memory, you should declare fn as pointer to const char.

const char *fn = "~/lyrics/";

Then you can see there are some errors. Here is a better solution:

char fn[MAX_SIZE] = "~/lyrics/";

Here MAX_SIZE shall be the sum of the size of "~/lyrics/", the maximum length of argv[1] and the length of ".txt".

This approach is not portable.

If using glibc you also might call asprintf() which just allocates as much memory as you need.

#include <stdio.h>

...

char * pFn = NULL;

if (-1 == asprintf(&pFn, "~/lyrics/%s.txt", argv+1);
{
  perror("asprintf()");
}
else
{
  ... /* use pFn */
}

free(pFn);

...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!