I'm almost certainly doing something very obviously dumb but I've been working at this for a while and I can't find a solution anywhere.
Basically I'm making a server and client, the client needs to send a username and password to the server. Everything seems to work fine if I place everything in the main function but when I try to space it out into the separate functions it seems to do some weird things so I think I'm not handling the pointers correctly. If I print tests and what not in the receiveStringData function the string is fetched from the client perfectly, it's just when I try to access the pointer back in the authenticate function. If I do the following code in the authenticate function...
char *username = receiveStringData(socket_id);
char *password = receiveStringData(socket_id);
printf("Username: %s", username);
than nothing prints. However, if I add a newline character it prints perfectly...
printf("Username: %s\n", username);
I could keep going on about the behavior but it'd take a while to list everything and I have a feeling that I'm doing something that is pretty obvious to someone with more experience so I'll include more details if requested but wont bother for now.
Here is the relevant code snippet (this is purely the server coding)...
bool authenticate(int socket_id);
char *receiveStringData(int socket_id);
int main(int argc, char *argv[])
{
bool authenticated = false;
if(!authenticated)
authenticated = authenticate(new_fd);
}
bool authenticate(int socket_id)
{
char *username = receiveStringData(socket_id);
char *password = receiveStringData(socket_id);
char *tempUsername = malloc(sizeof(char) * MAXDATASIZE);
char *tempPassword = malloc(sizeof(char) * MAXDATASIZE);
bool result = false;
//This logic of course only works when we assume the text file is correct as is provided to us
for(int i = 1; i <= userSize; i++)
{
//printf("Test1 ");
int stringPos = 0;
for(int j = 0; j < strlen(users[i]); j++)
{
if (users[i][j] == '\t' || users[i][j] == ' ')
{
stringPos++;
}
else if(stringPos > 0)
{
memcpy(tempUsername, users[i], sizeof(char) * (j - stringPos));
memcpy(tempPassword, users[i] + (sizeof(char) * j), sizeof(char) * strlen(users[i]) - j);
tempUsername[j - stringPos] = '\0';
tempPassword[strlen(users[i]) - j] = '\0';
break;
}
}
//printf("Test ");
if (strcmp(tempUsername, username) == 0 && strcmp(tempPassword, password) == 0)
{
printf("IT WORKED");
result = true;
}
}
free(username);
free(password);
free(tempUsername);
free(tempPassword);
return result;
}
char *receiveStringData(int socket_id)
{
int numbytes;
char *buf = malloc(sizeof(char) * MAXDATASIZE);
if ((numbytes = recv(socket_id, buf, MAXDATASIZE, 0)) == -1)
perror("connect");
buf[numbytes] = '\0';
return buf;
}