0

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?

7
  • 1
    Please show a minimal reproducible example, including where and how you allocate memory for buffer_list.array_of_buffers Commented Apr 22, 2020 at 18:17
  • how so? what does then calloc do? Commented Apr 22, 2020 at 18:26
  • Nevermind, I misread the code. Though you still don't show what inputs you give and what id is Commented Apr 22, 2020 at 18:26
  • ops i forgot change that id Commented Apr 22, 2020 at 18:27
  • Actually, calloc(0, means you allocate space for 0 elements - which is still 0 (and you are therefore not allowed to access any element via buffer_list.array_of_buffers[x]) Commented Apr 22, 2020 at 18:28

1 Answer 1

1

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) );
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.