Here's the main relevant method. It gets a string response through a program given to us. The sendCommand method outputs into response (so response has right output no questions asked). Then I removed the '\r' (not really important) and alter the "response". That works fine and is irrelevant to my question pretty much.
Code:
void get_messages() {
char response[ MAX_RESPONSE ] = "";
char lastNum[10];
sprintf(lastNum, "%d", lastMessage);
sendCommand(host, port, "GET-MESSAGES", user, password, lastNum, response);
char *temp;
int x = 0;
temp = response;
//removes /r
while(x < strlen(response)-2) {
if (response[x] != '\r')
*temp++ = response[x];
if (response[x] == '\r')
lastMessage++;
x++;
}
*temp = 0;
char str [100];
char str2 [100];
char strfinal[MAX_RESPONSE]= "";
int i;
messages = malloc(MAX_RESPONSE * sizeof(char));
if(strcmp(response, "NO-NEW-MESSAGES") != 0){
sscanf(response, "%d %s %[^\n]",i, str, str2);
sprintf(messages, "%d: %s - %s", i, str, str2);
}
else{
messages = "";
}
}
messages is printed down here after initial call of get_messages and then through every loop: (messages is global variable)
Code:
void * getMessagesThread(void * arg) {
// This code will be executed simultaneously with main()
// Get messages to get last message number. Discard the initial Messages
char response[ MAX_RESPONSE ] = "";
get_messages(); //the method posted above
while (1) {
// Get messages after last message number received.
get_messages();
// Print messages
printf("%s", messages);
// Sleep for ten seconds
usleep(2*1000*1000);
}
}
Now If I replace the sscanf and sprintf with messages = strdup(response), messages prints perfectly. keep that in mind.