Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a string literal to a char array, how is the string literal copied onto the stack?

I understand when you do char array[] = "string", the string literal "string" gets copied from the data segment to the stack. Is the string literal copied over character by character? Or the compiler gets the start and end address of the string literal and copies the entire string to the stack at one time?

thanks

like image 262
rabbit686 Avatar asked Apr 22 '13 17:04

rabbit686


1 Answers

The compiler does anything it “wants” to do, as long as the observed result is the same. Sometimes there is no copy at all.

The C standard does not specify how the copy is done, so the C implementation is free to achieve the result by any means. The only requirement the C standard imposes is that the observable results (such as text written to standard output) must be as defined.

When engineers are designing a C implementation to be high quality, they will spend some time considering the best ways to copy a string in such a situation, and they will seek to design a compiler that chooses the best way in each situation. A short string might be built in place by using “move immediate value” instructions. A long string might be copied by a call to memcpy. An intermediate string might be copied by an inlined call to memcpy, effectively a few instructions that move several bytes each.

When engineers are designing a cheap C implementation, something that just gets the job done so that code can be ported to machine but does not need to be fast, they will do whatever is easiest for them.

Sometimes a compiler will not copy the string at all: If the compiler can tell that you do not need a copy, there is no reason to make a copy. For example, if the compiler sees that you merely pass the string to printf and do not modify it at all, then the compiler get the same result without making a copy by passing the original to printf.

like image 81
Eric Postpischil Avatar answered Sep 18 '22 08:09

Eric Postpischil