MasterWizard
MasterWizard

Reputation: 877

glibc detected realloc(): invalid pointer

Im constantly getting this when I build on Qtcreator.

  *** glibc detected *** /home/Exxamples/EffectivCons: realloc(): invalid pointer:        0xb6fb5414 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x75ee2)[0xb6603ee2]
/lib/i386-linux-gnu/libc.so.6(realloc+0x25d)[0xb660856d]
/lib/i386-linux-gnu/libc.so.6(realloc+0x273)[0xb6608583]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData7reallocEi+0x37)[0xb6906e67]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData6appendEi+0x7c)[0xb6906f4c]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_ZN9QListData6appendEv+0x23)[0xb6906fd3]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(+0x1afa3e)[0xb6a05a3e]
/opt/Qt5.1.1/5.1.1/gcc/lib/libQt5Core.so.5(_Z21qRegisterResourceDataiPKhS0_S0_+0x216)[

This is my code, through the other questions on the website, I saw some users using malloc or realloc, but Im not using it, why am i getting an error?

  #include <termios.h>
    #include <string.h>
#include <stdlib.h>
#define BUFLEN 512
std::string numberToString(const int n);
void sendExpressivAnimation(int,EmoStateHandle eState);
void handleExpressivEvent(std::ostream& os, EmoEngineEventHandle expressivEvent);
bool handleUserInput();
void promptUser();
void nonblocking();
int getch();
int kbhit();
int createSocket();

int startSendPort = 30000;

struct termios initial_settings, new_settings;

int kbhit (void)
{
    struct timeval tv;
    fd_set rdfs;

    tv.tv_sec = 0;
    tv.tv_usec = 0;

    FD_ZERO(&rdfs);
    FD_SET (STDIN_FILENO, &rdfs);

    select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
    return FD_ISSET(STDIN_FILENO, &rdfs);
}

int main(int argc, char **argv)
{
    EmoEngineEventHandle eEvent = EE_EmoEngineEventCreate();
    EmoStateHandle eState       = EE_EmoStateCreate();
    unsigned int userID         = 0;
    const int CONTROL_PANEL_PORT = 3008;

    bool connected = false;

    if(EE_EngineRemoteConnect("127.0.0.1", CONTROL_PANEL_PORT)== EDK_OK)
    {
        std::cout <<"Emotiv Engine started" << std::endl;
        connected = true;
    }
    else
    {
        std::cout <<"Emotiv Engine failed !"<< std::endl;
        connected = false;
    }

    std::cout << "Type \"exit\" to quit, \"help\" to list available commands..." << std::endl;
    promptUser();

    int _socket;
    _socket = createSocket();

    if(connected)
    {

       nonblocking();
       fflush(stdin);
       while (true) {

            // Handle the user input
            //if (_kbhit()) {
                if (!handleUserInput()) {
                    break;
                }

            //}

            int state = EE_EngineGetNextEvent(eEvent);

            // New event needs to be handled
            if (state == EDK_OK) {

                EE_Event_t eventType = EE_EmoEngineEventGetType(eEvent);
                EE_EmoEngineEventGetUserId(eEvent, &userID);

                switch (eventType) {

                    // New headset connected, create a new socket to send the animation
                    case EE_UserAdded:
                    {
                        std::cout << std::endl << "New user " << userID << " added, sending Expressiv animation to ";
                        std::cout << "127.0.0.1" << ":" << startSendPort << "..." << std::endl;
                        promptUser();

                        break;
                    }

                    // Headset disconnected, remove the existing socket
                    case EE_UserRemoved:
                    {
                        std::cout << std::endl << "User " << userID << " has been removed." << std::endl;

                        promptUser();

                        break;
                    }

                    // Send the Expressiv animation if EmoState has been updated
                    case EE_EmoStateUpdated:
                    {
                        //std::cout << "New EmoState from user " << userID << "..." << std::endl;
                        EE_EmoEngineEventGetEmoState(eEvent, eState);

                        sendExpressivAnimation(_socket,eState);

                        break;
                    }

                    // Handle Expressiv training event
                    case EE_ExpressivEvent:
                    {
                        handleExpressivEvent(std::cout, eEvent);
                        break;
                    }

                    default:
                        break;
                }
            }
            else if (state != EDK_NO_EVENT) {
                std::cout << std::endl << "Internal error in Emotiv Engine!" << std::endl;
                break;
            }
        }
    }

    EE_EngineDisconnect();
    EE_EmoStateFree(eState);
    EE_EmoEngineEventFree(eEvent);

    return 0;
}


std::string numberToString(const int n) {
    char* buf;
    //_itoa(n, buf, 10);
    QString nStr = QString::number(n);
    buf = nStr.toLocal8Bit().data();
    return std::string(buf);
}


void sendExpressivAnimation(int _socket,EmoStateHandle eState) {

    std::ostringstream output;

    EE_ExpressivAlgo_t upperFaceType = ES_ExpressivGetUpperFaceAction(eState);
    EE_ExpressivAlgo_t lowerFaceType = ES_ExpressivGetLowerFaceAction(eState);

    float upperFaceAmp = ES_ExpressivGetUpperFaceActionPower(eState);
    float lowerFaceAmp = ES_ExpressivGetLowerFaceActionPower(eState);

    if (ES_ExpressivIsBlink(eState)) {
        output << "B,";
    }

    if (ES_ExpressivIsLeftWink(eState)) {
        output << "l,";
    }

    if (ES_ExpressivIsRightWink(eState)) {
        output << "r,";
    }

    if (ES_ExpressivIsLookingRight(eState)) {
        output << "R,";
    }

    if (ES_ExpressivIsLookingLeft(eState)) {
        output << "L,";
    }

    if (upperFaceAmp > 0.0) {
        switch (upperFaceType) {
            case EXP_EYEBROW:   output << "b";  break;
            case EXP_FURROW:    output << "f";  break;
            default:            break;
        }
        output << numberToString(static_cast<int>(upperFaceAmp*100.0f)) << ",";
    }

    if (lowerFaceAmp > 0.0) {
        switch (lowerFaceType) {
            case EXP_CLENCH:    output << "G";  break;
            case EXP_SMILE:     output << "S";  break;
            case EXP_LAUGH:     output << "H";  break;
            case EXP_SMIRK_LEFT:  output << "sl"; break;
            case EXP_SMIRK_RIGHT: output << "sr"; break;
            default:            break;
        }
        output << numberToString(static_cast<int>(lowerFaceAmp*100.0f)) << ",";
    }

    std::string outString = output.str();

    // Remove the last comma
    if (outString.length()) {
        outString.resize(outString.length()-1);
    }

    if (!outString.length()) {
        outString = std::string("neutral");
    }

    if(send(_socket, outString.c_str(), BUFLEN, 0)==-1)
        {
            std::cout<<"sending error"<<std::endl;
            //exit(1);
        }
}


void handleExpressivEvent(std::ostream& os, EmoEngineEventHandle expressivEvent) {

    unsigned int userID = 0;
    EE_EmoEngineEventGetUserId(expressivEvent, &userID);
    EE_ExpressivEvent_t eventType = EE_ExpressivEventGetType(expressivEvent);


    switch (eventType) {

        case EE_ExpressivTrainingStarted:
        {
            os << std::endl << "Expressiv training for user " << userID << " STARTED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingSucceeded:
        {
            os << std::endl << "Expressiv training for user " << userID << " SUCCEEDED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingFailed:
        {
            os << std::endl << "Expressiv training for user " << userID << " FAILED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingCompleted:
        {
            os << std::endl << "Expressiv training for user " << userID << " COMPLETED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingDataErased:
        {
            os << std::endl << "Expressiv training data for user " << userID << " ERASED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingRejected:
        {
            os << std::endl << "Expressiv training for user " << userID << " REJECTED!" << std::endl;
            break;
        }

        case EE_ExpressivTrainingReset:
        {
            os << std::endl << "Expressiv training for user " << userID << " RESET!" << std::endl;
            break;
        }

        case EE_ExpressivNoEvent:
        default:
            //@@ unhandled case
            assert(0);
            return;
    }
    promptUser();
}


bool handleUserInput() {



    static std::string inputBuffer;

    char c = getch();

    if ((int)c == 10) {

        std::cout << std::endl;
        std::string command;

        const size_t len = inputBuffer.length();
        command.reserve(len);

        // Convert the input to lower case first
        for (size_t i=0; i < len; i++) {
            command.append(1, tolower(inputBuffer.at(i)));
        }

        inputBuffer.clear();

        bool success = parseCommand(command, std::cout);
        promptUser();
        return success;
    }
    else {
        if ((int)c == 127) { // Backspace key
            if (inputBuffer.length()) {
                putchar('\b');
                putchar(' ');
                putchar('\b');
                inputBuffer.erase(inputBuffer.end()-1);
            }
        }
        else {
            std::cout << c;
            if(((int) c == 32) || ((int)c == 95) || (((int)c >= 97 && (int)c <=122)) || (((int)c >=48 && (int)c <= 57)))
                            inputBuffer.append(1,c);
        }
    }

    return true;
}

void promptUser()
{
    std::cout << "ExpressivDemo> "<<std::endl;
}

void nonblocking()
{
    tcgetattr(0, &initial_settings);
    new_settings = initial_settings;
    new_settings.c_lflag &= ~ICANON;
    new_settings.c_lflag &= ~ECHO;
    //new_settings.c_lflag &= ~ISIG;
    new_settings.c_cc[VMIN] = 0;
    new_settings.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &new_settings);

}

int getch()
{
    int r;
    unsigned char c=0;
    if((r = read(0, &c, sizeof(c))) < 0 )
    {
        return r;
    }
    else
    {
        return c;
    }
}

int createSocket()
{
    struct sockaddr_in si_other;
    int s, slen = sizeof(si_other);

    if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
        std::cout<<"socket"<<std::endl;

    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(startSendPort);
    if (inet_aton("127.0.0.1", &si_other.sin_addr)==0)
    {

        std::cout<<"intet_aton failed !"<<std::endl;
        //exit(1);
    }

    if(connect(s,(sockaddr*)&si_other,slen)==-1)
    {
        std::cout<<"connect failed !"<<std::endl;
       // exit(1);
    }

    return s;
     }

Upvotes: 0

Views: 1059

Answers (1)

rodrigo
rodrigo

Reputation: 98436

Your code is too big to be checked wholly. If you can reduce it to a SSCCE it will be easier for everybody.

Anyway, skimming over your code, only one thing catched my eye:

char *buf;
QString nStr = QString::number(n);
buf = nStr.toLocal8Bit().data();
return std::string(buf);

The call to toLocal8Bit() returns a temporary QByteArray and then you call its data() member function. The returned pointer is only valid during the lifetime of that temporary, that is, until the ending ;. After that the buf pointer is invalid and the next line renders undefined behavior.

You should do something like:

QString nStr = QString::number(n);
QByteArray a(nStr.toLocal8Bit());
char *buf = a.data();
return std::string(buf);

Or even better:

QString nStr = QString::number(n);
return std::string(nStr.toLocal8Bit().data());

Or just for show:

return std::string(QString::number(n).toLocal8Bit().data());

Upvotes: 1

Related Questions