user2793162
user2793162

Reputation:

When do we need deep copy in c

In this code:

struct test
{
    char *p;
};

struct test glob;
void someFunc(struct test);

int main()
{
    struct test X;
    X.p=malloc(10);
    someFunc(X);

    //free(X.p);  
}


void someFunc(struct test y)
{
    glob.p=y.p;
}

In C++ I think this is tricky because when someFunc ends, and y goes out of scope - if one has proper destructor and this is a class object - memory pointed by y.p will get freed after someFunc ends, and thus glob.p will point to garbage right?

Is this also the case in C considering the same code above? Or will glob.p point to usable memory after someFunc ends?

Upvotes: 1

Views: 123

Answers (3)

Matt Phillips
Matt Phillips

Reputation: 9691

After someFunc ends, glob.p will point to the memory allocated with your call to malloc in main. This is true whether this is compiled as a C or C++ program (with struct removed from the someFunc declaration in the c++ case). If test has a different definition as a c++ class, as you seem to be asking at the end, then what happens at the end of someFunc depends entirely on the particulars of this definition.

Upvotes: 0

Filipe Gonçalves
Filipe Gonçalves

Reputation: 21223

In C, after someFunc() ends, y is destroyed, but not what y.p points to. You can keep using the memory you allocated wherever you want until you call free() - that's one of the advantages of dynamic allocation (and one of its drawbacks too - with great power comes great responsibility.)

In C++, the same thing will happen, unless there's a destructor that deletes the pointer. In that case, yes, both glob.p and X.p would be invalid pointers.

Upvotes: 1

dornhege
dornhege

Reputation: 1500

In C++ this same code will work the same as in C. Both should be fine as you pass the pointer around. You just need to be aware who owns that and thus deletes it.

If you write a destructor as you said, you should usually also provide proper copy and assignment operators. http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming) to prevent things like invalid pointers.

If you don't then, yes, such code will be dangerous and you need to be very much aware of what you are doing (and especially why this way).

Upvotes: 0

Related Questions