a variable defined in a function is created on stack. then, when function call completed, the variable is vanished due to stack in/out.
the following code is passing a data structure
typedef struct
{
test_out_t output;
test_in_t input;
} message_t;
typedef struct
{
uint8_t len;
uint8_t* data_out;
} test_out_t;
typedef struct
{
uint8_t len;
uint8_t* data_in;
} test_in_t;
The function call is void test(message_t *msg);
in the function, I defined a array, and assigned the pointer points to this array(the memory location). However, when the function call completed, I am expecting the pointer points the value becomes undetermined/Zeros, since the stack variable is gone.
However, it still has the value of the stack variable if I call printf() inside the function.
with the following code, the msg.output.data_out contains the value of array which created in the function.
If comment out the printf inside the test(). the msg.output.data_out is all zeros.
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define DATA_SIZE (8)
typedef struct
{
uint8_t len;
uint8_t* data_out;
} test_out_t;
typedef struct
{
uint8_t len;
uint8_t* data_in;
} test_in_t;
typedef struct
{
test_out_t output;
test_in_t input;
} message_t;
void test(message_t *msg);
void test(message_t *msg)
{
uint8_t stackdata[DATA_SIZE];
memset(stackdata, 0, DATA_SIZE);
for (int i=0; i<DATA_SIZE; i++)
stackdata[i] = i+1;
msg->output.len = DATA_SIZE;
msg->output.data_out = stackdata;
uint8_t data2[msg->input.len];
memcpy(&data2, msg->input.data_in, msg->input.len);
for (int i=0; i<msg->input.len; i++)
printf("0x%X\t", data2[i]);
}
int main(void) {
message_t msg;
uint32_t data2 = 0x12345678;
msg.input.len = 4;
msg.input.data_in = (uint8_t*)&data2;
test(&msg);
printf("\n");
for (int i=0; i<msg.output.len; i++)
printf("0x%X\t", msg.output.data_out[i]);
return 0;
}
I assume something related to printf()
BTW, I am using online compiler to run the code.