-1

I am having trouble figuring out how to get a value from a nested structure that is being passed into a function. I am trying the following:

 13 int calcSize(struct rect **A) {
 14 
 15     int test;
 16 
 17     *A = malloc(sizeof(struct rect));
 18 
 19 //  (*A)->ne.x = (int *)malloc(sizeof(int));
 20     test = (*A)->ne.x;
 21     printf("%d",test);
 22 
 23     return 0;
 24 
 25 }
 26 
 27 
 28 int main () {
 29 
 30     int sum;
 31 
 32     struct rect *input;
 33     input = (struct rect*)malloc(sizeof(struct rect));
 34     input->ne.x = 4;
 35     input->ne.y = 6;
 36     input->nw.x = 2;
 37     input->nw.y = 6;
 38     input->se.x = 4;
 39     input->se.y = 2;
 40     input->sw.x = 2;
 41     input->sw.y = 2;
 42 
 43     printf("%d",input->sw.y);
 44 
 45     sum = calcSize(&input);
 46 
 47 
 48     return 0;
 49 }

I was looking for clarification regarding malloc'ing memory for this even though it's already defined? And also the dereferencing is a bit confusing given the nested structs and pointer.

Austin
  • 347
  • 7
  • 21
  • 1
    Why are you doing a `malloc` inside `calcSize()`? – John3136 Oct 30 '17 at 04:06
  • @John3136 I was trying to follow an example given. Does the pointer A not need space allocated for it? – Austin Oct 30 '17 at 04:08
  • 1
    Why use double pointers at all ? The malloc in the function is overwiting the malloc in main and causing a leak plus use of uninitialized data. – John3136 Oct 30 '17 at 04:10
  • For future questions, please study the concept of a [mcve]. The line numbers (though a good idea) break C syntax. Please give them, but make them comments. E.g. `/* 13 */` instead of `13`. – Yunnosch Oct 30 '17 at 06:22

1 Answers1

1

Couple of things:

1) You have a memory leak because *A = malloc(sizeof(struct rect)); reassigns the pointer which was previously allocated in main and not freed.

2) Don't cast the return value of malloc in C. Do I cast the result of malloc?

MFisherKDX
  • 2,840
  • 3
  • 14
  • 25
  • 3) Why use double pointers at all ? 4) `A` points to uninitialized data so `test = (*A)->ne.x;` is undefined behavior. – John3136 Oct 30 '17 at 04:11