有人可以为我解释这个吗?

时间:2017-05-05 13:02:57

标签: c memory tcp network-programming printf

Program received signal SIGSEGV, Segmentation fault.
memcpy ()
    at ../sysdeps/x86_64/multiarch/../multiarch/memmove-vec-unaligned-erms.S:143
143 ../sysdeps/x86_64/multiarch/../multiarch/memmove-vec-unaligned-erms.S: No such file or directory.
(gdb) bt
#0  memcpy ()
    at ../sysdeps/x86_64/multiarch/../multiarch/memmove-vec-unaligned-erms.S:143
#1  0x00007ffff764aa2e in __GI__IO_default_xsputn (f=0x7fffffffcf30, 
    data=<optimized out>, n=30) at genops.c:438
#2  0x00007ffff761c59c in _IO_vfprintf_internal (
    s=s@entry=0x7fffffffcf30, format=<optimized out>, 
    format@entry=0x55555555773f "%s/%s", ap=ap@entry=0x7fffffffd058)
    at vfprintf.c:1637
#3  0x00007ffff763e61b in __IO_vsprintf (
    string=0x3930313938393339 <error: Cannot access memory at address 0x3930313938393339>, format=0x55555555773f "%s/%s", 
    args=args@entry=0x7fffffffd058) at iovsprintf.c:42
#4  0x00007ffff7623717 in __sprintf (s=<optimized out>, 
    format=<optimized out>) at sprintf.c:32
#5  0x000055555555680e in take_action (
    hash=0x7fffffffd4d0 "4ef3065e42d1ba6d821e734b2957b264", 
    index=0x7fffffffd36c, filnamE=0x7fffffffd5d0 "fs", 
    time_s=0x7fffffffd4a0 "1493989109") at file_sync.c:652
#6  0x0000555555556f25 in run_client (port_no=10009) at file_sync.c:821
#7  0x00005555555571df in main (argc=3, argv=0x7fffffffdef8)
    at file_sync.c:923

我得到的代码是:

    char *fnam;
    int nn = sprintf(fnam,"%s/%s",cwd,filnam);
    fnam[nn] = '\0';

其中cwd是一个值为"/home/username/dir1/dir2/di3"的字符串 filnam有价值:fs

我知道这些是值,因为我已将它们打印出来。

有人可以为我解释这个错误吗?我似乎无法弄清楚这一点。请在这件事上给予我帮助!谢谢!

编辑:

好的,这是要求的声明:

char cwd[256];
getcwd(cwd, sizeof(cwd));
**// getting cwd here**

DIR *directory = NULL;
pdir = opendir(cwd);

if(directory ==  NULL){printf("\nDirectory bad!!\n");exit(1);}  
char * filnam;
struct dirent *uppp = NULL;
while( uppp = readdir(directory) ) 
{
    if(uppp == NULL){printf("\nproblemo. \n"); exit(1);}
    filnam = uppp->d_name;
    if(filnam[0] == '.') { continue; }
**// this is where I'm getting filename**



}

1 个答案:

答案 0 :(得分:4)

问题在于:

char *fnam;
int nn = sprintf(fnam,"%s/%s",cwd,filnam);
fnam[nn] = '\0';

fnam未初始化。

试试这个:

char fnam[500];
int nn = sprintf(fnam,"%s/%s",cwd,filnam);

// -> remove this, it's not necessary: 
//    fnam[nn] = '\0';