Search code examples
cpointersmemorymemory-managementallocation

Proper way to have two pointers point to the same memory chunk


I have a structure:

struct generic_attribute{
    int current_value;
    int previous_value;
};

And a constructor which outputs a pointer to this structure:

struct generic_attribute* construct_generic_attribute(int current_value){
    struct generic_attribute *ga_ptr;
    ga_ptr = malloc (sizeof (struct generic_attribute));
    ga_ptr->current_value = current_value;
    ga_ptr->previous_value = 0;
    return ga_ptr;
}

Now, in another function, I want to define a pointer and set it to point to the same address as the pointer that the above constructor outputs.

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args){
    ...
    struct generic_attribute* generic = malloc (sizeof(struct generic_attribute));
    generic = construct_generic_attribute(args[0]);
    ...
}

It looks to me that what I am doing here is this:

1) I define a pointer "generic" and allocate a memory chunk to hold an instance of generic_attribute structure.

2) I call a function construct_generic_attribute within which, the program once again allocates a memory chunk of size of a generic_attribute structure. It outputs a pointer to this memory chunk.

3) In construct_tagged_attribute I set "generic" pointer equal to the pointer output by the construct_generic_attribute function, so now both of them point to the same memory slot.

However, it appears that I am allocating twice as much memory as I need to allocate.

Is there a way for me to allocate memory only once without getting a segmentation fault for failing to allocate space for "generic" pointer? Alternatively, am I misunderstanding what is happening in this code?


Solution

  • struct generic_attribute* generic = construct_generic_attribute(args[0]);
    

    Should do the trick. Pointer variable is just that, a variable. You can trade pointer values around just like numbers.