0

这是我的代码:

tmpip = get_public_ip();
pubip = strtok(tmpip, "\n");
sprintf(buffer, "220 FTPUtils Server [%s]", pubip);
len_string = strlen(buffer)+1;
if(send(newsockd, &len_string, sizeof(len_string), 0) < 0){
    perror("Errore invio len buffer");
    onexit(newsockd, sockd, 0, 2);
}
if(send(newsockd, buffer, len_string, 0) < 0){
    perror("Errore durante l'invio");
    onexit(newsockd, sockd, 0, 2);
}
pubip = NULL;
free(tmpip);
memset(buffer, 0, sizeof(buffer));


if(recv(newsockd, &len_string, sizeof(len_string), MSG_WAITALL) < 0){
    perror("Errore ricezione len user buffer");
    onexit(newsockd, sockd, 0, 2);
}
if(recv(newsockd, buffer, len_string, 0) < 0){
    perror("Errore ricezione del nome utente");
    onexit(newsockd, sockd, 0, 2);
}       
user_string = strtok(buffer, " ");
username = strtok(NULL, "\n");
fprintf(stdout, "%s %s\n", user_string, username);
sprintf(saved_user, "%s", username);
memset(buffer, 0, sizeof(buffer));

if(recv(newsockd, &len_string, sizeof(len_string), MSG_WAITALL) < 0){
    perror("Errore ricezione len pass buffer");
    onexit(newsockd, sockd, 0, 2);
}
if(recv(newsockd, buffer, len_string, 0) < 0){
    perror("Errore ricezione password");
    onexit(newsockd, sockd, 0, 2);
}
pass_string = strtok(buffer, " ");
password = strtok(NULL, "\n");
fprintf(stdout, "%s %s\n", pass_string, password);
memset(buffer, 0, sizeof(buffer));

printf("%s %s\n", username, password);

我上次调试时遇到问题:它没有printf打印到标准输出!为什么我的指针(用户名和密码)被清除了??? 这很奇怪,因为 2完美地工作,但最后一个没有......

fprintfprintf

4

1 回答 1

5

username和都password 指向内部的位置buffer。就是这样strtok工作的。

换句话说,当您将缓冲区memset归零时,您正在将内存归零usernamepassword指向。一个简单的解决方法是复制该内存:

username = strtok(NULL, "\n");
username = strdup(username);

Notestrdup不是标准的,但使用mallocand很容易实现strcpy

于 2012-09-02T13:45:56.403 回答