I have a inline function defined as following:
inline string Change(char *pointer) {
string str;
char temp[32] = "";
sprintf(temp,"%c:%c:%c:%c:%c:%c", //line 1
temp[0],temp[1],temp[2],
temp[3],temp[4],temp[5],
);
str = temp;
return str;
}
when I use memory leak tool to check it, it indicates line 1(marked above) is memory leak. What is the problem of the above code?
I created fully compilable example:
#include <string>
#include <iostream>
#include <cstdio>
std::string Change( char * ) {
std::string str;
char temp[32] = "";
sprintf(temp,"%c:%c:%c:%c:%c:%c", //line 1
temp[0],temp[1],temp[2],
temp[3],temp[4],temp[5]
);
str = temp;
return str;
}
int main()
{
char a[]={"abaaaaa2"};
std::cout<<Change(a)<<std::endl;
}
When running under valgrind, I get no leaks detected:
==16829==
==16829== HEAP SUMMARY:
==16829== in use at exit: 0 bytes in 0 blocks
==16829== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==16829==
==16829== All heap blocks were freed -- no leaks are possible
==16829==
==16829== For counts of detected and suppressed errors, rerun with: -v
==16829== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 15 from 8)
If you want to know exactly where is the leak you can use plugins. you can pick out a plugin that will be convenient for you. For me, it is deleaker. There are so many developments in this field!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With