Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ gcc string inlining

Tags:

c++

gcc

g++

inline

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.

like image 681
user3575889 Avatar asked May 10 '15 00:05

user3575889


2 Answers

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);           \
        }()
like image 172
jxh Avatar answered Nov 11 '22 12:11

jxh


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.

like image 39
RichN Avatar answered Nov 11 '22 11:11

RichN