strcat and malloc

Go To


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:

  1. Malloc a string
  2. Using for loop, call strcat 2 times
  3. Free the string

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

  • strcat string 1: AABB
  • strcat string 2: CCDD
  • strcat string 3: EEFF

Actual Output:

  • strcat string 1: AABB
  • strcat string 2: AABBCCDD
  • strcat string 3: AABBCCDDEEFF

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);
        curNode = curNode->next;
2012-04-03 19:53
by user1305850
can we see some code snippets - kevingreen 2012-04-03 19:54
show us the actual code otherwise we can't find the error in the code - twain249 2012-04-03 19:55


After ptr=malloc(…), before strcat(), initialize the space with *ptr = '\0';. The memory returned by malloc() is usually not zeroed.

2012-04-03 19:58
by Luca Rocchi
That did it, thanks - user1305850 2012-04-03 20:00


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

2012-04-03 19:56
by RyanS
This 'answer' should probably have been a comment. The code arrived a couple of minutes after you posted this. Since its material isn't directly germane to the problem, I suggest it should be deleted (but I'd rather not down-vote to force your hand) - Jonathan Leffler 2017-03-19 17:19