简体   繁体   中英

strcat and malloc

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;
    }
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM