Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory allocation within dynamic allocated memory on C++

I would like to ask a question concerning dynamic memory allocation in C++. I understand that the nature of the problem I am about to propose is easy to resolve using simple C++ techniques, but for this particular exercise I have to use a more C-like approach. Let me set an example:

I have the following structs:

typedef struct A{
    B *b;
    int a;
}

typedef struct B{
    C *c;
    int x;
}

typedef struct C{
    int y;
}

And let's assume this main:

int main(){
    A test;
    test.a = 1;

    test.b = (B*)calloc(2,sizeof(B));

    test.b[0].c = (C*)calloc(2,sizeof(C)); 
    test.b[0].x = 2; 
    test.b[0].c[0].y = 3;
    test.b[0].c[1].y = 4;

    test.b[1].c = (C*)calloc(2,sizeof(C));
    test.b[1].x = 5;
    test.b[1].c[0].y = 6;
    test.b[1].c[1].y = 7;
}

So my question is as follows: What happens? Is there a possibility the memory blocks allocated for test.b[i].c to overlap with the memory blocks that have been previously allocated for test.b? If that is possible to happen how can I prevent it from happening? If it is not possible can you explain exactly how calloc() allocates memory? I would really appreciate a numeric example.

like image 598
Vasileios Karavasilis Avatar asked Oct 03 '22 17:10

Vasileios Karavasilis


1 Answers

Is there a possibility the memory blocks allocated for test.b[i].c to overlap with the memory blocks that have been previously allocated for test.b?

No.

If that is possible to happen how can I prevent it from happening?

It can't happen, so don't worry.

If it is not possible can you explain exactly how calloc() allocates memory?

Every time you call calloc, it gives you back a pointer to a block of zero-initialized memory large enough to hold the requested number of objects, or NULL if it fails. As long as you don't get NULL back, you have nothing else to worry about.

I'm not sure what you mean by "numeric example".

like image 159
Carl Norum Avatar answered Oct 07 '22 18:10

Carl Norum