Question

My code runs properly and has no memory leaks. However, I am getting valgrind errors:

==6304== 14 errors in context 4 of 4:
==6304== Invalid write of size 1
==6304==    at 0x4A0808F: __GI_strcpy (mc_replace_strmem.c:443)
==6304==    by 0x401453: main (calc.cpp:200)
==6304==  Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304==    by 0x401431: main (calc.cpp:199)

==6304== 4 errors in context 2 of 4:
==6304== Invalid read of size 1
==6304==    at 0x39ADE3B0C0: ____strtod_l_internal (in /lib64/libc-2.12.so)
==6304==    by 0x401471: main (calc.cpp:203)
==6304==  Address 0x4c390f1 is 0 bytes after a block of size 1 alloc'd
==6304==    at 0x4A075BC: operator new(unsigned long) (vg_replace_malloc.c:298)
==6304==    by 0x401431: main (calc.cpp:199)

errors 1 and 3 are identical to 2 and 4, respectively besides the initial address

What do these errors mean and how do I fix them?

 int main(){

    //Dlist is a double ended list. Each Node has a datum,
    //a pointer to the previous Node and a pointer to the next Node
    Dlist<double> hold;
    Dlist<double>* stack = &hold;

    string* s = new string;
    bool run = true;
    while (run && cin >> *s){

        char* c = new char;
        strcpy(c, s->c_str());   //valgrind errors here

        if (isdigit(c[0]))
            stack->insertFront(atof(c));

        else{
            switch(*c){
                //calculator functions
            }

        delete c;
        c = 0;
  }
delete s;
s = 0;
Was it helpful?

Solution

There are a host of generally innocuous warnings that valgrind will throw from stdlib functions since they "cheat" a little. But this is not the case here:

char* c = new char; // this is bad

only allocates a char - not a buffer of chars, try:

char* c = new char[s->size()+1];

and then change the delete to:

delete [] c;

OTHER TIPS

char* c = new char; The size of c is 1 and to copy even 1 character string you need two characters long buffer (2nd character to hold the null terminator)

Right here:

    char* c = new char;

You're only allocating a single char. Allocate an array instead:

    char* c = new char[str->length() + 1];

also remember to call delete[] instead. You allocate +1 to make space for the null termination of the string.

    char* c = new char;

You are allocating a single char, and then copying a string into that memory which is too long to fit. You need to allocate a big enough array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top