0

When creating a struct, I often zero it using struct initialization:

struct MyStruct data = { 0 };

However, I have a very large (200mb) struct that I'm allocating, and because it has strict alignment needs (math library using AVX), I'm allocating it using _mm_alloc:

struct MyStruct* data = (struct MyStruct*)_mm_malloc( sizeof (struct MyStruct), 32 );

To zero this struct, memset works fine. However, if I try to use struct initialization here, it crashes with a Segmentation Fault:

*data = (struct MyStruct) { 0 };

Am I doing this improperly for a dynamically allocated struct? Or is there some other reason why a strictly-aligned block of allocated memory can't be initialized in this way?

Nairou
  • 3,585
  • 5
  • 29
  • 47
  • 1
    my first guess is `(struct MyStruct)` tries to create a temporary struct on the stack to copy into `*data`, and at 200MB blows it up. Default stack size in linux in my experience is 8MB. – yano Apr 08 '21 at 15:13
  • A compound literal is equivalent to declaring a local scope object. See the linked duplicate. Doesn't matter if it's a struct, array etc, you'll get stack overflow. – Lundin Apr 09 '21 at 06:47

2 Answers2

4

When you do this:

*data = (struct MyStruct) { 0 };

You're using a compound literal which creates a temporary object in the local scope. Such an object will typically reside on the stack, so if this object is on the order of 200MB in size, you'll overflow the stack with this temporary object.

Using memset is the best way to zero out this array.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

That depends how smart tho compiler is.

#define SIZE (200*1024*1024)

struct st 
{
    int i[SIZE];
};

struct st *foo(void)
{
    struct st *x = malloc(sizeof(*x));

    *x = (struct st){0};
    return x;
}

gcc allocates memory on the stack for the compound literal.

clang does not.

You need to assume that in the worst-case scenario the compiler will allocate the memory for it.

https://godbolt.org/z/P4jscoPaf

If the initialization is more complex clang places created compound literal in the static storage (maybe because of the size)

https://godbolt.org/z/bEbExWdEq

0___________
  • 60,014
  • 4
  • 34
  • 74