分段错误 - strcat [英] Segmentation fault- strcat

查看:27
本文介绍了分段错误 - strcat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

#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 编译它,编译器没有给出错误消息.但是当我运行它时,我收到错误消息:

I compiled it using gcc -g -o file file.c and the compiler gave no error messages. But when I run it I get the error message:

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 到它你覆盖它的堆栈分配的末尾并进入堆栈..因此出现分段错误.

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.

您可以尝试以下方法:

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

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

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

或者你可以这样做:

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!

这篇关于分段错误 - strcat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆