Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack around the variable was corrupted

Tags:

c

gets

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.

like image 533
user1673206 Avatar asked Dec 15 '22 17:12

user1673206


1 Answers

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"
    ...
}
like image 53
Sergey Kalinichenko Avatar answered Jan 04 '23 16:01

Sergey Kalinichenko