Fredy
Fredy

Reputation: 3

C/ C++ basic struct not working Visual studio

I have 2 simple structs and one has array of the second one.

When accesing the second one my program crashes in visual studio but not in codeblocks.

So one line is not working and another one is.

Can somebody explain why?

    struct buffer {
    uint64_t size;
    void* data;

};

struct list_of_buffers {
    uint64_t number_of_buffers;
    bool* active_buffers;
    struct buffer* array_of_buffers;
}buffer_list;




void alloc_fun(int size){
   buffer_list.array_of_buffers = (struct buffer*)calloc(0, sizeof(struct buffer) * size);

   //this one makes my program crash
   buffer_list.array_of_buffers[0].data = NULL;    

   //this one doesnt
   struct buffer tmp = buffer_list.array_of_buffers[0];
   tmp.data = NULL;
   }

Can somebody explain please?

Upvotes: 0

Views: 218

Answers (1)

zdan
zdan

Reputation: 29450

You are asking calloc for a buffer of 0 elements:

 buffer_list.array_of_buffers = (struct buffer*)calloc(0, sizeof(struct buffer) * size);

what that returns is implementation defined as per the docs:

If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

So my guess is that visual studio is returning a null pointer (thus the crash) while code blocks is not. I think this is what you want:

buffer_list.array_of_buffers = (struct buffer*)calloc(size, sizeof(struct buffer) );

Upvotes: 1

Related Questions