I am having a problem with gets
.
The purpose is to get input from the user until he hits the 'Enter'.
This is the code:
struct LinkedListNode* executeSection2()
{
char inputArr [3] = {'\0'};
struct LinkedListNode* newNode;
struct LinkedListNode* head = NULL;
gets (inputArr);
while (inputArr[0] != 0) // The user didn't press "Enter"
{
newNode=newLinkedListNode();
newNode->tree=newHuffmanNode(inputArr[0],atoi(inputArr+2));
head = addNode(&head, newNode);
gets (inputArr);
}
head = buildHuffmanTree(&head);
return head;
}
It seems OK, the user hits the 'Enter', the code go out from the while, but after the return, I get the error message:
Stack around the variable 'inputArr' was corrupted
I guess I dont read the input from the keyboard properly. I will be happy for some guidness.
Thanks.
This error is a perfect illustration to the reason why gets
has been deprecated: it is prone to buffer overruns, which corrupt stack or whatever memory happens to be near the end of your buffer. When the user enters more than two characters, the first three get placed into the buffer, and the rest go into whatever happens to be in the memory after it, causing undefined behavior.
You need to replace the call of gets
with a call of fgets
, which accepts the size of the buffer, end prevents user input from overrunning it:
fgets (inputArr, 3, stdin);
on every
while
iteration, the user hit enter and at the end, when he wants to stop, he hits only enter.
fgets
considers '\n'
part of the string, so when the user hits enter the only character in the returned string will be '\n'
:
while (inputArr[0] != '\n') { // The user didn't press "Enter"
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With