5

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.

1
  • 1
    You can also check the pointers returned from calloc that are not NULL just to be sure. It is safer. Commented Jun 25, 2013 at 23:04

1 Answer 1

5

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the quick answer. It really takes some stress off my shoulders, yet I still have to find what is wrong with my code. I know what calloc does on a higher level (meaning the pointer part). By numeric example I mean an example involving certain memory block allocation. Let's say when I use calloc for the first time it allocates memory blocks 0x0000 to 0x0010 etc. It would really help me understand how calloc works behind the scenes. If you could provide that too I would really appreciate it.
That's very system-dependent - there are plenty of open source C library implementations around on the web if you'd like to look at one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.