Reputation: 59
So I have defined a structure struct process
with name
as of its attributs. I also a global variable struct process *table[3]
.
So inside one of my functions, I did:
struct process *new_element = table[0];
new_element = malloc(sizeof(struct process));
new_element->name = some_name;
...
After that, when I try to access the name with table[0]->name
it shows me an memory access error.
But if I use malloc
on table[0]
it works:
table[0] = malloc(sizeof(struct process));
struct process *new_element = table[0];
new_element->name = some_name;
...
I dont understand why the first case failed, when I point new_element
towards table[0]
then use malloc
on it, shouldnt it allocates memory on table[0]
?
Upvotes: 1
Views: 55
Reputation: 81
When yo do this:
struct process *new_element = table[0]; // this make variable points to memory table[0]
new_element = malloc(sizeof(struct process)); // in this point you don't creating memory for table[0] you are creating memory and assigning th
at to new_element new_element->name = some_name; // here is an new memory
After that, when yo try table[0]->name. here is not memory table[0] is undefined
table[0] = malloc(sizeof(struct process)); // Here you create a memory for table[0]
struct process *new_element = table[0]; // here you point to the memory wich table[0] points to
new_element->name = some_name; // Here is not undefined and can be accesible
Upvotes: 0
Reputation: 26066
struct process *new_element = table[0];
This copies the pointer (which is a value, similar to an integer) into a new variable called new_element
. When you modify it later (assigning it what malloc()
returns), table[0]
is not updated.
shouldnt it allocates memory on table[0]?
No, it does not. The address is saved to new_element
, but table[0]
is not modified. If you want to do it that way, you would need to copy the address later on:
table[0] = new_element;
This doesn`t copy the element, just the pointer (the address of where it is in memory)!
Upvotes: 3