当我尝试释放 dataToWrite 时,我不确定为什么在 if 循环中会抛出垃圾值。它在 else 循环中工作正常。谁能帮我这个?
FILE *readFilePointer = NULL;
Message_buf outputMsgBuffer;
char fileData[PIPE_BUF];
char *dataToWrite=NULL;
readFilePointer = fopen(fileToReadFrom, "r");
if (readFilePointer == NULL)
{
outputMsgBuffer.messageType=1;
dataToWrite=(char *)malloc(strlen(strcat(fileToReadFrom," does not exists!!"))+1);
memset(dataToWrite,0,strlen(dataToWrite));
dataToWrite=strcat(fileToReadFrom," does not exists!!");
strcat(outputMsgBuffer.messageText,dataToWrite);
memset(dataToWrite,0,strlen(dataToWrite)+1);
free(dataToWrite);
}
else
{
//outputMsgBuffer.messageText[0] = '\0';
while (fgets(fileData, sizeof(fileData), readFilePointer) != NULL)
{
dataToWrite=(char *)malloc(sizeof(fileData));
memset(dataToWrite,0,strlen(dataToWrite));
strcpy(dataToWrite,fileData);
strcat(outputMsgBuffer.messageText,dataToWrite);
free(dataToWrite);
}
fclose(readFilePointer);
}
outputMsgBuffer.messageType=1;
outputMsgBuffer.messageLength=strlen(outputMsgBuffer.messageText);
mesg_send(fd,&outputMsgBuffer);
}