views:

79

answers:

2

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 any 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?

+6  A: 

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.

Matthew Flaschen
so the problem I'm having is not becasue of the stack stuff is because of this NULL-terminator.
okami
Probably, strcpy will copy characters up to and including the first NULL it finds. If you don't provide the terminator it will keep going until it finds one in memory. Google `buffer overflow`, or `buffer overrun`.
Blastfurnace
+2  A: 

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 !!! 
Bander