Reputation: 141
Currently, I need to strcat() 2 strings together. The catch is that I have to do this 3 times. (Total of 6 concatenations). The procedure is this, repeated 3 times using loops:
The problem is that even after I free the string and re-malloc, the strcat seems to keep on concatenating the previous string.
For example:
Expected Output from AA BB CC DD EE FF
Actual Output:
Does anyone know why it's doing this?
void sendInitialHand(card * deck) {
char * stringToSend;
playerNode * curNode;
curNode = housePlayers.head;
for (int i=0; i<housePlayers.playerCount; i++) {
stringToSend = malloc(sizeof(char)*6);
for (int j=0; j<52; j++) {
if (deck[j].inPlay == curNode->playerFD) {
strcat(stringToSend, deck[j].identifier);
}
}
for (int j=0; j<52; j++) {
if (deck[j].inPlay == 10) {
strcat(stringToSend, deck[j].identifier);
}
}
printf("[NETWORK] Send %d the following: %s\n", curNode->playerFD, stringToSend);
//send(curNode->playerFD, stringToSend, 6, 0);
free(stringToSend);
curNode = curNode->next;
}
}
Upvotes: 0
Views: 4392
Reputation: 6464
After ptr=malloc(…)
, before strcat()
, initialize the space with *ptr = '\0';
. The memory returned by malloc()
is usually not zeroed.
Upvotes: 1
Reputation: 4194
Examine your looping structure using printf statements, it's likely that you aren't freeing what you think are when you think you are. Will edit answer based on code..
You only re-malloc, which just says hey I'm going to write here.. which is what you already said. Try to free/re-initialize the variable
Upvotes: 0