【问题标题】:Segmentation fault while running the binary file copied by C program运行C程序复制的二进制文件时出现分段错误
【发布时间】:2015-04-15 21:04:21
【问题描述】:

我有一个 C 程序来复制已编译(可执行)“Hello World!”的二进制文件。程序。

下面是它的代码。

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

int main()
{
    /* File pointer for source and target files. */
    FILE *fs, *ft;
    char ch;

    /* Open the source file in binary read mode. */
    fs = fopen("a.out","rb");
    if (fs == NULL)
    {
        printf("Error opening source file.\n");
        exit(1);
    }

    /* Open the target file in binary write mode. */
    ft = fopen("hello","wb");
    if (ft == NULL)
    {
        printf("Error opening target file.\n ");
        fclose(fs);
        exit(2);
    }

    while((ch = fgetc(fs)) != EOF)
    {
        fputc(ch, ft);
    }

    fclose(fs);
    fclose(ft);
    return 0;
}

我已经编译到上面的程序并给出了可执行文件名称'file10'。

a.out 是 hello world 程序的可执行文件(二进制)。

-bash-4.1$ ./a.out
Hello World!
-bash-4.1$

现在我运行上面的程序,以便将 a.out 复制到“hello”二进制文件中。

-bash-4.1$ ./file10
-bash-4.1$

这将创建二进制文件“hello”。

接下来我尝试运行这个二进制文件。

-bash-4.1$ ./hello
-bash: ./hello: Permission denied
-bash-4.1$

我的权限被拒绝。接下来我更改权限。

-bash-4.1$ chmod 777 hello
-bash-4.1$

现在,当我运行“hello”时,我遇到了分段错误。

-bash-4.1$ ./hello
Segmentation fault
-bash-4.1$

为什么会出现分段错误?不能像我在上面的程序中那样复制 C 程序的可执行文件吗?

谢谢。

【问题讨论】:

    标签: c file-io segmentation-fault binaryfiles


    【解决方案1】:

    您的变量ch 类型错误。它的类型应该是int,而不是char。通过将 fgetc 的结果存储到 char 中,您可以将值 255 和 EOF 折叠成一个值,从而在您第一次遇到值为 255 的字节时停止。

    【讨论】:

    • 但仍不清楚这是如何导致段错误的?
    • @bare_metal 当您在中途切断可执行文件然后运行它时会发生什么??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 2013-11-30
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多