Re: Structure having pointers
- From: AnticitizenOne <anticitizen.one@xxxxxxxxx>
- Date: Sun, 29 Jul 2007 04:26:11 -0700
Hi,
when you write b=a you copy the memory of the struct instance a in b.
In this way you copy the pointer p of a in b. Now a.p and b.p point to
the same memory.
To make a depth copy of the struct you have to write a function:
struct Sample* SampleCopy(struct Sample* src)
{
struct Sample* b=NULL;
b=(struct Sample*)malloc(sizeof(struct Sample));
b.i=src.i;
b.p=(char*)malloc(sizeof(char)*(strlen(src.p)+1));
memcpy(b.p,src.p);
return b;
}
int main()
{
Sample a;
a.p = (char*)malloc(10);
Sample *b;
b = SampleCopy(&a);
free(a.p);
free(a);
printf("%s",b->p); //should work!!
}
I think in this way you may solve your problem... if I've understood.
Probably I've committed some errors in the code.. but I've not a
reference now!
Bye
Gio
On 29 Lug, 12:20, sam_...@xxxxxxxxxxx wrote:
Hi,
I have the following Struct,
Struct Sample
{
int i;
char *p;
};
int main()
{
Sample a;
a.p = malloc(10);
Sample b;
b = a;
}
Now i think a shallow copy is done and if i destry only on the object
there would be a dangling pointer.
How do i overcome this problem as C structures don't support
functions?
Thanks in advance!!!
.
- Follow-Ups:
- Re: Structure having pointers
- From: santosh
- Re: Structure having pointers
- References:
- Structure having pointers
- From: sam_cit
- Structure having pointers
- Prev by Date: Re: function for clockticks since 1980?
- Next by Date: Re: Malcolm's new book
- Previous by thread: Structure having pointers
- Next by thread: Re: Structure having pointers
- Index(es):
Relevant Pages
|