Reputation: 17243
Please consider the following piece of code:
void bar(Thing* thing) {
some_buffer[some_index++] = *thing;
}
void foo(void) {
Thing thing;
bar(&thing);
}
Does some_buffer[some_index++] = *thing;
create a copy of the original thing
?
Is this code guaranteed to be safe, in terms of memory? Because thing
in foo
is obviously dead when foo
exits.
Upvotes: 2
Views: 64
Reputation: 154305
Does dereferencing an argument create a local copy of it?
The below code conceptually creates a local copy and then copies. The emitting code may simple read and assign in one step without an intermediate local copy - or may not - depends on the compiler.
some_buffer[some_index++] = *thing;
Is this code guaranteed to be safe
No, not certainly.
Thing
is not initialized, so depending on its definition, code may have traps or UB. Best to post a minimal reproducible example.
As the location of some_index
and some_buffer
's data are unknown and may overlap thing
in some strange way. This obliges some_buffer[some_index++] = *thing;
to take that into account. Research restrict
to negate this unlikelihood. Better: avoid global data.
Otherwise, looks OK.
Upvotes: 3
Reputation: 15586
Does
some_buffer[some_index++] = *thing;
create a copy of the originalthing
?
Yes. It creates a copy of *thing
and assigns it to some_buffer[some_index]
, then increments some_index
.
Is this code guaranteed to be safe, in terms of memory? Because
thing
infoo
is obviously dead whenfoo
exits.
Yes. thing
is in scope for the entire duration of these two functions, and foo
does not pass the address of thing
to its caller (as it's a void
function).
Your code is completely valid.
Upvotes: 1