Re: Structure having pointers



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



.



Relevant Pages

  • Re: Memory Structure Pointer Problems
    ... typedef struct sta { ... char* name; ... int num_cmpnds; ... A pointer to a struct cmp is almost ...
    (comp.lang.c)
  • Re: Another spinoza challenge
    ... You should test against the int type's limits: ... typedef struct complex ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: Another spinoza challenge
    ... int main{ ... using struct and typedef. ... a pointer to an integer ... A macro is preferable because it is replaced by inline code, ...
    (comp.lang.c)
  • Re: [RFC][PATCH 1/6] memcg: fix pre_destory handler
    ... returns struct cgroup of id. ... SwapCgroup uses array of "pointer" to record the owner of swaps. ... struct cgroup_id is freed by RCU. ... changed interface from pointer to "int" ...
    (Linux-Kernel)
  • Re: destroying objects
    ... and then destroys the allocated memory. ... I included a pointer to this function in the emplist ... typedef struct _employee ... int eid; ...
    (comp.lang.c)