Skip to content

Instantly share code, notes, and snippets.

@Bueddl
Created September 15, 2016 10:30
Show Gist options
  • Save Bueddl/275e568135da61ae332ac3a9d2f14143 to your computer and use it in GitHub Desktop.
Save Bueddl/275e568135da61ae332ac3a9d2f14143 to your computer and use it in GitHub Desktop.
gcc zero-length array extension demo
#include <stdio.h>
#include <malloc.h>
struct static_buffer {
size_t size;
char buffer[0];
};
struct static_buffer* alloc_buffer(size_t size)
{
struct static_buffer *buf;
size_t alloc_size;
alloc_size = sizeof(struct static_buffer) + size;
printf("sizeof(struct static_buffer) = %lu\n"
"size = %lu\n"
"Allocating %lu bytes\n",
sizeof(struct static_buffer),
size,
alloc_size);
buf = (struct static_buffer*)malloc(alloc_size);
if (!buf)
return NULL;
buf->size = size;
return buf;
}
int main()
{
int i;
struct static_buffer *my_buf;
// Alloc buffer to store 32 bytes
my_buf = alloc_buffer(0x20);
// Fill with marker
for (i = 0; i < my_buf->size; ++i)
my_buf->buffer[i] = i % 0xFF;
// Dump buffer object
puts("Buffer:");
for (i = 0; i < sizeof(struct static_buffer) + 0x20; ++i)
{
printf("%02x ", ((unsigned char*)my_buf)[i]);
if (i % 0xF == 0xE)
putchar('\n');
}
putchar('\n');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment