I am not sure why a garbage value is being thrown in the if loop when i try to free dataToWrite. It works fine in else loop.
Can anyone help me with this?
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);
}
You are not initialising the allocated memory, so calling
strlenondataToWriteinvokes undefined behaviour.Also, you seem to not be aware of the fact that
strcatmodifies the memory pointed to by its first argument, and returns a pointer to it,throws away the just-allocated memory.