0
votes

I'm getting this error from Valgrind:

  • ==31251== Memcheck, a memory error detector
  • ==31251== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al.
  • ==31251== Using Valgrind-3.6.0 and LibVEX; rerun with -h for copyright info
  • ==31251== Command: ./a.out
  • ==31251== Parent PID: 31250
  • ==31251==
  • ==31251== Conditional jump or move depends on uninitialised value(s)
  • ==31251== at 0x400B9F: strcat2(char*, char*) (main.clean.cpp:30)
  • ==31251== by 0x400C4E: main (main.clean.cpp:50)
  • ==31251==
  • ==31251==
  • ==31251== HEAP SUMMARY:
  • ==31251== in use at exit: 0 bytes in 0 blocks
  • ==31251== total heap usage: 2 allocs, 2 frees, 3,010 bytes allocated
  • ==31251==
  • ==31251== All heap blocks were freed -- no leaks are possible
  • ==31251==
  • ==31251== For counts of detected and suppressed errors, rerun with: -v
  • ==31251== Use --track-origins=yes to see where uninitialised values come from
  • ==31251== ERROR SUMMARY: 3 errors from 1 contexts (suppressed: 6 from 6)

I can't see what the problem is with my code...

#include <iostream>
using namespace std;

void strcat2(char* a, char* b);

int main()
{
    char *a = new char[2010], *b = new char[1000];
    while (cin.getline(a, 1000) && cin.getline(b, 1000))
    {
        cout << "a = \"" << a << "\";" << endl;
        cout << "strcat2(a, \"" << b << "\");" << endl;
        strcat2(a, b);
        cout << "a = \"" << a << "\";" << endl << endl;
    }
    delete[] a;
    a = NULL;
    delete[] b;
    b = NULL;


    return 0;
}

void strcat2(char* a, char* b){
    while (*a){ 
        a++; 
    }
    while((*a++ = *b++) != '\0'){ 
        *a++ = *b++;
    }


}
1
Isn't the *a++ = *b++; inside the loop superfluous?Adri C.S.

1 Answers

1
votes

Yep as @Adri C.S. is saying:

while((*a++ = *b++) != '\0') { 
    *a++ = *b++;
}

make it:

while((*a++ = *b++) != '\0');

Note: The answer is given by @Adri C.S