What is the cause of this Valgrind error?

Valgrind complains about substr call.

string Message::nextField(string& input) { int posSeparator = input.find_first_of(SEPARATOR); string temp; temp = input.substr(0, posSeparator); //Error points to this line input.erase(0, posSeparator + 1); return temp; } 

Error:
290 bytes in 12 blocks are definitely lost in the loss record 1 of 1
What the function does is basically parse the input, returning the parts of the string separated by the SEPARATOR character. This function is called from another class method with the following definition:

 void doSomething(string input) { input.erase(0,2); string temp = nextField(input); this->room = atoi(temp.c_str()); temp = input; this->money = atoi(temp.c_str()); } 

There is nothing more strange or important. I use the default setting for Valgrind from profiling Eclipse Indigo Valgrind. Any ideas?

+6
source share
3 answers

You do not check if posSeparator is really different from string :: npos - this may cause problems when erasing. It's a wild shot, but it can still fix the mistake.

0
source

This is probably not a bug in the code. This error may be reported due to implementation details of the C ++ standard library. To verify this, try the following from the Valgrind FAQ :

With GCC 2.91, 2.95, 3.0, and 3.1, compile the entire source using the STL with -D__USE_MALLOC. Caution! This has been removed from GCC since version 3.3.

With GCC 3.2.2 and later, you must export the GLIBCPP_FORCE_NEW environment variable before starting your program.

With GCC 3.4 and later, this variable changed its name to GLIBCXX_FORCE_NEW.

+2
source

You probably have an error somewhere else in your source. I tried to replicate the error using the following code:

 #include <string> #include <iostream> #include <cstdlib> using namespace std; const char SEPARATOR = ':'; struct Foo { public: int room; int money; void doSomething(string input) { input.erase(0,2); string temp = nextField(input); this->room = atoi(temp.c_str()); temp = input; this->money = atoi(temp.c_str()); } string nextField(string& input) { int posSeparator = input.find_first_of(SEPARATOR); string temp; temp = input.substr(0, posSeparator); //Error points to this line input.erase(0, posSeparator + 1); return temp; } }; int main() { Foo f; f.doSomething("--234:12"); std::cout << f.room << " - " << f.money << std::endl; } 

Then run valgrind:

 valgrind --tool=memcheck <executable> 

and output:

 HEAP SUMMARY: in use at exit: 0 bytes in 0 blocks total heap usage: 2 allocs, 2 frees, 61 bytes allocated All heap blocks were freed -- no leaks are possible For counts of detected and suppressed errors, rerun with: -v ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4) 

So maybe your problem is not in this part of the code

+1
source

Source: https://habr.com/ru/post/897795/


All Articles