I apologise if this has been answered before but I have been driving myself mad searching for an answer. I have been using malloc to create an array:
char *message = (char*) malloc(31 *sizeof(char));
To get the user to enter a message of maximum 30 characters:
fgets(message, 30, stdin);
In another function I have then tried to convert the message to lower case and store it in another string (of hopefully equal length as the message).
int length_message = strlen(message) - 1;
char *temp1 = (char*) malloc(length_message * sizeof(char));
for(int i=0; message[i] != '\0'; i++)
{
temp1[i] = tolower(message[i]);
}
But when I come to display the new string
puts(temp1);
It shows my input message followed by a whole load of gibberish on a new line. I cannot understand where this is coming from.
Furthermore upon checking the length of my temp1 array and the value I created for length message, using:
printf("length of temp array: %d", strlen(temp1));
printf("length of message: %d\n", length_message);
Which returned the desired length_message (number of characters input by user in message) but the wrong number for the length of my temp array! Have I incorrectly allocated the memory for my temporary array or have I not written to that array correctly?
From what I have read on other threads, I seem to have a buffer overflow error? How do I keep this in check?
Thanks in advance!