I want to force strings to be allocated into local variables dynamically at run-time via assembly instructions without the string occupying memory in a data section (such as the read only data section).
The following seems to work perfectly:
char foo[] = "bar";
The assembly code becomes:
movl $7496034, 40(%esp)
Thus, foo
is initialized with "bar"
via the movl
instruction at run-time.
How can I force it to happen on all string operations?
For example, if I pass a string literal into a function:
testfunc("bar");
The string "bar"
will be allocated in a section in this case.
The technique you show only works for your special case. In general, the compiler is free to place the contents of strings into the section. For example, with this small tweak:
char foo[] = "bar\0";
The string will now appear in the read only data section.
Knowing that the technique is not guaranteed to always work, you can use a macro to automate the technique so that you can pass strings to functions without using pointers to the read only section.
#define string_invoke(Func, Str) \
[]() -> decltype(Func(NULL)) { \
char foo[] = Str; \
return Func(foo); \
}()
You have a four-character string you want to initialize with four characters ("bar" plus the null-terminator.) The compiler recognizes an opportunity for an awesome micro-optimization and saves a four-byte integer into the string which has the same bit pattern as "bar". On 64-bit machines, the compiler might also use this technique for 8-character strings. Wonderful! But don't expect this optimization to be applicable wherever you use C strings.
When a function takes a C string as a parameter, for instance, it's expecting a pointer to an array, not an integer.
Contorting you code to force specific compiler optimizations is a great way to write unmaintainable, brittle code. You're better off writing clear code using efficient algorithms and enjoying whatever awesome optimizations the compiler can apply.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With