I have this structure:
class Base
{
public:
void doACopy(char* strToCopy) {
strcpy(str, strToCopy);
}
private:
char str[4];
};
class Derived : public Base
{
public:
void doSomething() {
char toCopy[4];
toCopy[0] = 'a'; toCopy[1] = 'b'; toCopy[2] = 'c';
Base::doACopy(toCopy); // is there an开发者_开发问答y problem passing toCopy here?
}
};
I know toCopy is allocated on stack. Is there any problem on passing this array to super, in this case Derived::doACopy?
There's no problem with the stack memory being destroyed. toCopy
is valid until doSomething
returns, and by that time the strcpy is complete.
But they must both be length 4, and you must NUL-terminate toCopy
:
private:
char str[4];
// ...
char toCopy[4];
toCopy[0] = 'a'; toCopy[1] = 'b'; toCopy[2] = 'c';
toCopy[3] = '\0';
As is, there's no NUL-terminator (or even room), and this will cause a buffer overflow during strcpy
.
char toCopy[4]; will be available and exist until the end of method doSomething . And regarding the problem that you have ...As Naveen said ... it's because you didn't put a terminator char "NULL"... to fix this issue you may rewrite the definition of toCopy are as following :-
char toCopy[4] = {0};
I highly recommend you to use string instead of plain array of char ... so if we rewrite the code with new changes ... it will be like this ...
#include<string>
using std::string;
class Base
{
public:
void doACopy(string & strToCopy) {
str = strToCopy;
}
private:
string str;
};
class Derived : public Base
{
public:
void doSomething() {
string toCopy = "abc";
Base::doACopy(toCopy); // is there any problem passing toCopy here?
}
};
is not easy !!!
精彩评论