Does this constitute a memory leak?
#include <stdio.h>
#include <string.h>
class tst {
public:
char *a;
tst() {
printf("Default constructor.\n");
a = new char[1];
a[0] = 0;
}
tst(const char *b) {
printf("Construct from char * %s.\n", b);
a = new char[strlen(b)];
strcpy(a, b);
}
tst(const tst ©) {
printf("Copy constructor for %s.\n", copy.a);
a = new char[strlen(copy.a)];
strcpy(a, copy.a);
}
~tst() {
printf("Destructor for %s.\n", this->a);
delete [] a;
}
};
tst &func3() {
printf("FUNC3\n");
tst *a = new tst("3456");
return *a; // <---- THIS (Copy constructor is called)
}
Basically, I want func3() to return either a reference or value of (but
not a pointer to) an object of type tst, but I'm not sure if this
solution results in a memory leak or not. Also, func3 must have no
output parameters.
A weird thing that happens is that in this test example, a copy
constructor for a is called. But in the real problem which made me
create this test, the copy constructor is NOT called and I don't see the
difference - I have the same instantiation (through a constructor which
takes const char * as a parameter) and the same return-by-reference case
there.
If it will make any sense, here's the original function:
String &DocumentBuilder::GetSubstring(const char *WholeDoc, int CPos,
int Len) {
printf("Getting substring beginning at %d of length %d.\n", CPos, Len);
char *resStr = new char[Len + 1];
resStr = (char *)memset(resStr, '0', Len);
resStr[Len] = 0;
String *inResult = new String(resStr);
String &Result = *inResult;
delete [] resStr;
for (int x = CPos; x < CPos + Len; ++x)
Result.SetChar(x - CPos, WholeDoc[x]);
Result.SetChar(Len, 0);
printf("After getting substring, value is %s.\n", (char *)Result);
return *inResult; // Copy constructor is NOT called
}
Basically, this function gets a substring from WholeDoc array which in
general contains binary data with some ASCII character sequences. String
represents a string, a class I've created to simplify their
manipulation. Constructors in String class are the same as the ones in
tst class I wrote. String::SetChar(int x, char a) sets character on
position x to value a. Operator (char *) converts an object of type
String to a character array containing characters that make up the string.
DocumentBuilder is a class that converts binary data contained in the
array passed to GetSubstring to something more manageable in further
processing. GetSubstring is a private static function in that class. I
don't think this should play much of a role here.
I'd be thankful if someone can explain what's going on in each example also.
Nikola