printf 中 C++ client/server 应用程序的分段错误

Segmentation fault on a C++ client/server application at printf

我正在尝试从客户端读取 username/password 并将其传输到服务器。我也在尝试动态分配字符串(我不太了解它,正在尝试学习它)并且我很确定存在问题。在最后 2 个 printf 中,我遇到了分段错误(核心已转储)。

int nrbytes;
char *Usercl,*Passcl;
if( read (tdl.cl, &nrbytes, sizeof(int)) <= 0 )
{
    printf("[server]Thread - %d\n",tdl.idThread);
    perror("Read() error\n ");
}

Usercl = new char[nrbytes+1];
if( read (tdl.cl, &Usercl, sizeof(nrbytes)) <= 0 )
{
    printf("[server]Thread - %d\n",tdl.idThread);
    perror("Read() error\n ");
}

if( read (tdl.cl, &nrbytes, sizeof(int)) <= 0 )
{
    printf("[server]Thread - %d\n",tdl.idThread);
    perror("Read() error\n ");
}
Passcl = new char[nrbytes+1];
if( read (tdl.cl, &Passcl, sizeof(nrbytes)) <= 0 )
{
    printf("[server]Thread - %d\n",tdl.idThread);
    perror("Read() error\n ");
}
printf("[server]Thread - %d\n. User:%s\n",tdl.idThread,Usercl);
printf("[server]Thread - %d\n. Pass:%s\n",tdl.idThread,Passcl);

我在最后 2 个 printf 上遇到分段错误(核心已转储)。

您的 Usercl 和 Passcl 已经是指针。在他们的两个读取调用中删除“&”。

我修好了。我做了你告诉我的一切,现在它起作用了。谢谢!