C stack usage with temporary structures

2019-08-03 02:50发布

I work with embedded stuff, so, I use special C compiler C30 for MCUs. I'm confused about its behavior with temporary structures.

But, maybe I don't know something, and it's intended behavior?

Consider little code:

typedef struct {
   int a;
   int b;
} T_TestStruct1;

void test1(T_TestStruct1 *p_test_struct)
{
   /* do something */
}

And these calls to test1() :

void some_function()
{

   {
      T_TestStruct1 par = {
         .a = 1,
         .b = 1,
      };
      test1(&par);
   }

   {
      T_TestStruct1 par = {
         .a = 2,
         .b = 2,
      };
      test1(&par);
   }

}

Everything is OK here: just one instance of T_TestStruct1 is allocated in the stack. But I like to use shorter expressions:

void some_function()
{
   test1(&(T_TestStruct1){
      .a = 1,
      .b = 1,
      });

   test1(&(T_TestStruct1){
      .a = 2,
      .b = 2,
      });
}

Then, both structures {.a = 1, .b = 1} and {.a = 2, .b = 2} are allocated in the stack. But, in my opninion, they should not be. Only one instance is actually needed.

Just by chance, I tried that:

void some_function()
{
   {
      test1(&(T_TestStruct1){
         .a = 1,
         .b = 1,
         });
   }

   {
      test1(&(T_TestStruct1){
         .a = 2,
         .b = 2,
         });
   }
}

Result is the same.

So, is it intended behavor, or is it a bug in the compiler?

标签: c stack
2条回答
冷血范
2楼-- · 2019-08-03 03:42

There is no guarantee (in the C standard) that your non-volatile variables will exist at all in the compiled code after all optimizations. Likewise there's no guarantee that your compiled code is the fastest and the smallest and uses the minimum amount of resources (that includes the stack).

If this is something critical for you, you could either play with the optimization options of your compiler or write this code in assembly (inline or not).

查看更多
爷的心禁止访问
3楼-- · 2019-08-03 03:44

Actually I don't see the benefit of the expression causing you troubles. It makes the code just less readable.

But apart from that: You can't predict whether the compiler creates a stackframes including two instances of the structure or not. This is up to the compiler and his optimization engine. In case you really need control about the allocation of memory here and you really need to optimize, I'd suggest to allocate this variable once and explicitly reuse it for both calls, leaving a comment why you do it like this.

查看更多
登录 后发表回答