我有两个文件,我想使用 memcpy 将一个文件的内容复制到另一个文件。但是我收到此错误 Segmentation Fault (core dumped)
。我的主要
int main( int argc, char * argv[] ){
int d1;
int d2;
char *a;
char *b;
d1 = da_open_r(argv[1]); // open file READ ONLY
d2 = da_open_w(argv[2]); // open file to WRITE
a = (char*)da_mmap(d1); // map first file
b = (char*)da_mmap(d2); // map second file
memcpy(b, a, 10); // I think this line is bad
kp_test_munamp(a, 10 ); //
kp_test_munamp(b, 10 );
kp_test_close(d1); // close 1 file
kp_test_close(d2); // close 2 file
return 0;
}
这是我的 da_mmap
和 kp_test_munamp
void *da_mmap(int d){
mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_SHARED, d, 0);
}
int kp_test_munamp( void *a, int size ){
int rv;
rv = munmap( a, size );
if( rv != 0 ){
puts( "munmap failed" );
abort();
}
return 1;
}
我已经尝试解决这个问题将近两个小时了,但我仍然不知道哪里出了问题。 编辑我的完整代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
#include <string.h>
int da_open_r(const char *name);
int da_open_w(const char *name);
void *da_mmap(int d);
int kp_test_munamp( void *a, int size );
int kp_test_close(int fd);
int da_open_r(const char *name){
int dskr;
dskr = open( name, O_RDWR );
if( dskr == -1 ){
perror( name );
exit( 255 );
}
printf( "dskr1 = %d\n", dskr );
return dskr;
}
int da_open_w(const char *name){
int dskr;
dskr = open( name, O_RDWR );
if( dskr == -1 ){
perror( name );
exit( 255 );
}
printf( "dskr2 = %d\n", dskr );
return dskr;
}
void *da_mmap(int d){
void *a = NULL;
a = mmap(NULL, 10, PROT_WRITE, MAP_SHARED, d, 0);
if( a == MAP_FAILED ){
perror( "mmap failed" );
abort();
}
return a;
}
int kp_test_munamp( void *a, int size ){
int rv;
rv = munmap( a, size );
if( rv == -1 ){
puts( "munmap failed" );
abort();
}
return 1;
}
int kp_test_close(int fd){
int rv;
rv = close( fd );
if( rv != 0 ) perror ( "close() failed" );
else puts( "closed" );
return rv;
}
int main( int argc, char * argv[] ){
int d1;
int d2;
char *a;
char *b;
d1 = da_open_r(argv[1]); // read only
d2 = da_open_w(argv[2]); // WRITE
a = (char*)da_mmap(d1);
b = (char*)da_mmap(d2);
memcpy(b, a, 10); // I think this line is bad
kp_test_munamp(a, 10 );
kp_test_munamp(b, 10 );
kp_test_close(d1);
kp_test_close(d2);
return 0;
}
最佳答案
da_mmap()
不返回任何东西!这导致 a
和 b
的值成为垃圾并且很可能指向无效内存,这反过来又导致 memcpy()
失败对它采取行动时。
添加返回语句
void * da_mmap(int d) {
return mmap(NULL, 10, PROT_READ|PROT_WRITE, MAP_SHARED, d, 0);
}
您还应该通过执行以下操作来测试映射的结果:
{
void * pvtmp = da_mmap(d1); // map first file
if (MAP_FAILED == pvtmp)
{
perror("da_mmap() failed");
exit(1);
}
a = pvtmp;
}
b
也是如此。
引用 munmap()
的包装器。更正这里的错误测试。然而,按照惯例,返回 0
表示成功(返回 -1
表示失败)。
关于c - mmap 和 memcpy 使用和 Segmentation Fault (core dumped) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014286/