Home > front end >  How to fix: double free or corruption (out) Aborted (core dumped) in C
How to fix: double free or corruption (out) Aborted (core dumped) in C

Time:05-28

I've recently been working on a C project of mine, and I ran into a problem with the executable:

    std::string commanddata;
    std::string input;
    std::string cmdname;
    int commandlength = 0;
    if (commandlength == 0){}else{} // This is so that G   doesn't complain that I have got a variable and never used it (I'm compiling at -Werror)
    while (true)
    {        
        input = DS_IO.kscanf(">>>"); // This is a specific function to get input from the user
        // Record the command length
        int commandlength = sizeof(input);

        // Make sure that the user doesn't just send us nothing
        if (commandlength <= 0)
            {
                continue;
            }
            else
            {
                // Get the first word from the command
            std::stringstream sstream(input);
            sstream >> cmdname;
            // Loops through the input string to remove everything up to and including a space delimiter
            for (int i = 0; i <= commandlength; i  )
            {
                if (input[i] == 32)
                {
                    commanddata = input;
                    commanddata.erase(input.begin(), input.begin()   i);
                    break;
                }
                else
                {
                    continue;
                }
            }
            // print out the data to make sure it's all working
            std::cout << "What you entered: " << input << std::endl;
            std::cout << "The command name: " << cmdname << std::endl;
            std::cout << "The command metadata: " << commanddata << std::endl;
        }
    }   

The code works fine, but my problem is as soon as it reaches the end of the loop, it freaks out and gives this error:

EXPECTED BEHAVIOUR:

chemeriov@mikumputer:~/dev/DigitalSledgehammer$ ./a.out
>>>echo Hello world
What you entered: Hello world
The command name: echo
The command metadata: Hello world
>>>

EXPERIENCED BEHAVIOUR:

chemeriov@mikumputer:~/dev/DigitalSledgehammer$ ./a.out
>>>echo Hello world
What you entered:  Hello world
The command name: echo
The command metadata:  Hello world

double free or corruption (out)
Aborted (core dumped)
chemeriov@mikumputer:~/dev/DigitalSledgehammer$ 

How to fix this?

CodePudding user response:

The sizeof(input) is a constant number, like 16 bytes. To find length of the string, call input.length() method.

CodePudding user response:

Thanks very much to @Soonts, who fixed my problem!

** Another issue, commanddata.erase( input.begin() is obviously wrong, a container can’t erase ranges inside other unrelated containers. A correct usage is something.erase(something.begin(), .. **

You can clearly tell I'm a noob at this :)

  • Related