strcat和malloc [英] strcat and malloc
问题描述
当前,我需要将strcat()2个字符串放在一起.问题是我必须做3次. (总共6个串联). 步骤是这样,使用循环重复3次:
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:
- 分配一个字符串
- 使用循环,调用strcat 2次
- 释放字符串
问题是,即使我释放了字符串并重新分配了内存,strcat似乎仍然继续连接前一个字符串.
The problem is that even after I free the string and re-malloc, the strcat seems to keep on concatenating the previous string.
例如:
AA BB CC DD EE FF的预期输出
- strcat字符串1:AABB
- strcat字符串2:CCDD
- strcat字符串3:EEFF
实际输出:
- strcat字符串1:AABB
- strcat字符串2:AABBCCDD
- 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;
}
}
推荐答案
在ptr=malloc(…)
之后,在strcat()
之前,用*ptr = '\0';
初始化空间. malloc()
返回的内存通常不为零.
After ptr=malloc(…)
, before strcat()
, initialize the space with *ptr = '\0';
. The memory returned by malloc()
is usually not zeroed.
这篇关于strcat和malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!