Segmentation fault while running the binary file copied by C program
I have a C program to copy the Binary file of a compiled (executable) "Hello World!" program.
Below is its code.
#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;
}
I have compiled to above program and gave the executable name 'file10'.
a.out is the executable (binary) of a hello world program.
-bash-4.1$ ./a.out
Hello World!
-bash-4.1$
Now I run the above program so that a.out will be copied to "hello" binary file.
-bash-4.1$ ./file10
-bash-4.1$
This creates the binary file "hello".
Next I try to run this binary file.
-bash-4.1$ ./hello
-bash: ./hello: Permission denied
-bash-4.1$
I get permission denied. Next I change the permissions.
-bash-4.1$ chmod 777 hello
-bash-4.1$
Now when I run "hello" I get a segmentation fault.
-bash-4.1$ ./hello
Segmentation fault
-bash-4.1$
Why is there a segmentation fault? Can't executable of C program be copied like how I did in the program above?
Thanks.
Your variable ch
has the wrong type. It should have type int
, not char
. By storing the result of fgetc
into a char
, you're collapsing the values 255 and EOF
into a single value and thus stopping the first time you encounter a byte with value 255.
上一篇: 通过特殊功能分段故障
下一篇: 运行C程序复制的二进制文件时出现分段错误