简体   繁体   English

strcat 和 malloc

[英]strcat and malloc

Currently, I need to strcat() 2 strings together.目前,我需要将 strcat() 2 个字符串放在一起。 The catch is that I have to do this 3 times.问题是我必须这样做 3 次。 (Total of 6 concatenations). (总共 6 个连接)。 The procedure is this, repeated 3 times using loops:程序是这样的,使用循环重复 3 次:

  1. Malloc a string Malloc 一个字符串
  2. Using for loop, call strcat 2 times使用for循环,调用strcat 2次
  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.问题是,即使在我释放字符串并重新 malloc 之后,strcat 似乎仍在继续连接前一个字符串。

For example:例如:

Expected Output from AA BB CC DD EE FF预计来自 AA BB CC DD EE FF 的 Output

  • strcat string 1: AABB strcat 字符串 1:AABB
  • strcat string 2: CCDD strcat 字符串 2:CCDD
  • strcat string 3: EEFF strcat 字符串 3:EEFF

Actual Output:实际 Output:

  • strcat string 1: AABB strcat 字符串 1:AABB
  • strcat string 2: AABBCCDD strcat 字符串 2:AABBCCDD
  • strcat string 3: AABBCCDDEEFF strcat 字符串 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';ptr=malloc(…)之后,在strcat()之前,用*ptr = '\0';初始化空间. . The memory returned by malloc() is usually not zeroed. malloc()返回的 memory 通常不归零。

Examine your looping structure using printf statements, it's likely that you aren't freeing what you think are when you think you are.使用 printf 语句检查您的循环结构,很可能您没有释放您认为是的东西。 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.您只重新 malloc,这只是说嘿我要写在这里..这就是您已经说过的。 Try to free/re-initialize the variable尝试释放/重新初始化变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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