#include <cstring>
#include <cstdio>
#include <cstdlib>
struct Block {
int32_t size;
u_int8_t data[0];
};
int main(int argc, char **argv) {
Block block;
Block *ptr = █
u_int8_t data_buffer[] = {1, 3, 0, 1, 3, 4, 5, 5, 6, 2, 2, 3};
void *sdata = (void *)data_buffer;
void *ndata = (void*)ptr->data;
printf("data ptr: %p\n", ptr->data); // 0x7ffe53275340
printf("ndata: %p\n", ndata); // 0x7ffe53275340
memcpy((void*)ndata, &data_buffer, sizeof(void*));
printf("ndata: %p\n", ndata); // 0x505040301000301
printf("*(&data_buffer): %p\n", *(&data_buffer)); // 0x7ffe53275330
printf("data ptr: %p\n", ptr->data); // 0x7ffe53275340
for(int i{0}; i<12; i++) {
printf("%d ", (((u_int8_t*)(ptr->data))[i]));
}
printf("\n");
return 0;
}
The code block is as above,
I am so confused that after memcpy function, why ndata would be changed to 0x505040301000301, a so strange value?
I have googled flexible array, but can not find exactly this kind of example. Any help would be great appreciated.
ndata(akaptr->dataakablock.data) points to? Your program exhibits undefined behavior by way of a buffer overrun. You are scribbling all over the stack, overwriting your own local variables.0x505040301000301happens to be the contents ofdata_bufferu_int8_t data[0];is not a flexible array member. It's a "struct hack" and it's undefined behavior.u_int8_t data[];would be a flexible array member. Zero-sized arrays used like that are a buggy GCC extension. Don't use them.