0

I have following situation. My aim is to make a and b such that both of them points to same memory. But the condition is that both of them are pointers. How do i do it?

struct myStruct
{
struct anotherStruct* anoStrct;
};
main()
{
   struct myStruct *a=( struct myStruct*)malloc(sizeof( struct myStruct));
   struct myStruct *b=( struct myStruct*)malloc(sizeof( struct myStruct));
   a=b;


}
sattu
  • 632
  • 1
  • 22
  • 37
  • 1
    In your code, the memory zone which you first `malloc` (the original `a`) is lost so is a memory leak. Use a memory leak detector (e.g. `valgrind` on Linux) and your debugger. – Basile Starynkevitch Apr 11 '13 at 07:44

2 Answers2

6

You could allocate space for one pointer for example, a as

struct myStruct *a= malloc(sizeof( struct myStruct));

and assign this pointer to b as

struct myStruct *b = a;

EDIT: When you copy pointers and use them for some operations, you also would have to be careful w.r.t. copying i.e. whether the copy is a shallow-copy or deep-copy. Please do refer to What is the difference between a deep copy and a shallow copy? for more details.

In the aforementioned code segment, if the following statements are executed after initializing b with a, you will encounter a segmentation fault as the original pointer has already been freed.

free(b);
a->anoStrct = malloc(sizeof(struct anotherStruct));
Community
  • 1
  • 1
Ganesh
  • 5,880
  • 2
  • 36
  • 54
  • 4
    You shouldn't need to cast malloc, see http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – ed_me Apr 11 '13 at 07:48
  • @chrisw69 Thanks.. I just copied the statement from the question. I was in the middle of editing when my system crashed :) – Ganesh Apr 11 '13 at 07:49
3
struct myStruct *a=malloc(sizeof(*a));
struct myStruct *b=a;

Note that since a and b both point to the same memory, updates to one will (obviously) also affect the other. Also, you must only later call free on one of the pointers.

Your suggested code also leaves both variables pointing to the same memory. It leaks the memory that was originally allocated for a however.

simonc
  • 41,632
  • 12
  • 85
  • 103