c - 段错误 - strcat

标签 c segmentation-fault valgrind

这是我的代码:

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

void main(int arge, char *argv[])
{
    FILE *f1;
    char ch,*fn="~/lyrics/";
    strcat(fn,argv[1]);
    strcat(fn,".txt");
    if( (f1 = fopen(fn,"r"))==NULL )
    {
        printf("\nWrong filename\n%s not found",argv[1]);
        return;
    }
    while((ch=getw(f1))!=EOF)
    {
        printf("%c",ch);
    }
}

我使用 gcc -g -o file file.c 编译它,编译器没有给出任何错误消息。但是当我运行它时,我收到错误消息:

Segmentation fault (core dumped)
Bad permissions for mapped region at address 0x8048659 at 0x402C36B: strcat 
(in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so) by 0x80484D6: main (lyrics.c:9)

谁能帮帮我?

最佳答案

您在 fn 中没有足够的空间。通过 strcat'ing 到它,你覆盖了它的堆栈分配的末尾并进入堆栈......因此出现段错误。

您可以尝试以下方法:

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

您只需确保整个路径和文件名可以容纳 255 个字符。

或者你可以这样做:

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" );

而且你肯定已经为字符串分配了足够的空间。只是不要忘记在完成后释放它!

关于c - 段错误 - strcat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13901209/

相关文章:

gcc - Oracle Linux 中的 Valgrind 安装错误

c - 使用 rand() 时输出范围内的随机数

c - 打开 ELF 文件并检查

c - 我在将 malloc 与字符串指针一起使用时出现段错误

python-3.x - Ubuntu Mate 上的 Tkinter 段错误中的 Matplotlib

c - C中的Valgrind检查是否有泄漏

c++ - 如何使用 gnu 缩进在函数名和括号之间设置空格?

c - '=' 标记之前的预期构造函数、析构函数或类型转换

c - 字符串格式在 fprintf 中有效,但在 sprintf 中不起作用,出现段错误

c - 不干净地从 C 子进程退出而没有 valgrind 提示?