strcat and malloc

2020-05-05 18:36发布

问题:

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);
        free(stringToSend);
        curNode = curNode->next;
    }
}

回答1:

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



回答2:

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



标签: c string malloc