复制文件时出现分段错误
我是初学者,我正在尝试将大小约为 33MB(精确地说是 33136KB)的非常大的文本文件的内容复制到新文件。我在运行程序时遇到分段错误。只有 16KB 被复制到我的新文件中。 我要复制的文件的名称是“test_file3”,我的新文件的名称是“newfile”。我在虚拟机中的 CentOS-5 中完成这一切。 详细信息如下:
[root@localhost decomp_trials]# cat read_file.c
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv [] )
{
FILE *ifp, *ofp;
char *ptr;
ifp = fopen ( argv [ 1 ], "r" );
ofp = fopen ( argv [ 2 ], "a" );
for ( ptr = malloc ( 10 ); fread ( ptr, 1, 10, ifp ); )
fprintf ( ofp, ptr );
fclose ( ifp );
fclose ( ofp );
return 0;
}
[root@localhost decomp_trials]# cc read_file.c -o read_file
[root@localhost decomp_trials]# ./read_file /root/sys_cl_huk_ajh/imp/copy_hook7/test_file3 newfile
Segmentation fault
[root@localhost decomp_trials]# du -s newfile
16 newfile
[root@localhost decomp_trials]# pwd
/root/sys_cl_huk_ajh/pro_jnk/decomp_trials
[root@localhost decomp_trials]# du -s ../../imp/copy_hook7/test_file3
33136 ../../imp/copy_hook7/test_file3
[root@localhost decomp_trials]#
请告诉我我可能做错了什么。有没有更好的方法呢?请帮帮我
I'm a beginner and I'm trying to copy the content of a very large text file of size around 33MB ( 33136KB precisely ) to a new file. I'm getting segmentation fault while running the program. Only 16KB is getting copied to my new file.
The name of file which I'm to copy is "test_file3" and my new file's name is "newfile". I'm doing all this in CentOS-5 in virtual box.
Here is the details:
[root@localhost decomp_trials]# cat read_file.c
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv [] )
{
FILE *ifp, *ofp;
char *ptr;
ifp = fopen ( argv [ 1 ], "r" );
ofp = fopen ( argv [ 2 ], "a" );
for ( ptr = malloc ( 10 ); fread ( ptr, 1, 10, ifp ); )
fprintf ( ofp, ptr );
fclose ( ifp );
fclose ( ofp );
return 0;
}
[root@localhost decomp_trials]# cc read_file.c -o read_file
[root@localhost decomp_trials]# ./read_file /root/sys_cl_huk_ajh/imp/copy_hook7/test_file3 newfile
Segmentation fault
[root@localhost decomp_trials]# du -s newfile
16 newfile
[root@localhost decomp_trials]# pwd
/root/sys_cl_huk_ajh/pro_jnk/decomp_trials
[root@localhost decomp_trials]# du -s ../../imp/copy_hook7/test_file3
33136 ../../imp/copy_hook7/test_file3
[root@localhost decomp_trials]#
Please tell me what I'm possibly doing wrong. Is there any better method? Please help me out
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用
fprintf
;它将第二个参数视为格式字符串。使用fwrite
。至于为什么出现段错误,请考虑如果您的输入数据碰巧包含
%s
会发生什么。然后,fprintf 将开始遍历堆栈,读取随机数据,直到找到 0 值字节(空终止符)。这很容易最终进入不属于应用程序的内存。Don't use
fprintf
; it treats its second argument as a format string. Usefwrite
.As to why it seg-faults, consider what happens if your input data happens to contain e.g.
%s
.fprintf
will then start walking through the stack, reading random data until it finds a 0-valued byte (a null terminator). This could easily end up walking into memory that isn't owned by the application.