-2

I was trying to find the space complexity of the following code:

void f(int arr[], int n){
    int m=0; 
    for(int i=1; i<n*n; ++i)
        for(int k=0; k<n*n; k+=i){
            m=(m>k)?m:k; 
            printf("1");
        }
    free(malloc(m)); 
}

the answer is n^2, however I don't quite understand how the memory allocation works here. I mean, why do we put the malloc inside the free? Doesn't it mean that we don't allocate any memory at all (because we free it right away? Or does it still count?).

Thanks!

Anna
  • 27
  • 5
  • 2
    Malloc will allocate the memory, return the pointer and pass it to free() and it's then freed. It counts – Zorgatone Mar 02 '16 at 13:17
  • 2
    IMO there's no reason to malloc and free like that – Zorgatone Mar 02 '16 at 13:18
  • @Olaf The code compiles fine. What do you think is wrong with it? – JeremyP Mar 02 '16 at 13:37
  • @JeremyP: Sorry, I overlooked the declaration of `k` in the inner loop. The rest stands, however. And `arr` is not even used. – too honest for this site Mar 02 '16 at 13:41
  • @Olaf I suspect this is a homework question.Also, I'd be surprised if `free(malloc(n))` is ever optimised away because `malloc()` has side effects that the compiler doesn't know about. – JeremyP Mar 02 '16 at 13:48
  • @JeremyP: You might be surprised how much a modern compiler knows about the standard library functions. The combination of `feee(malloc())` has no _required_ side-effects by the standard. They very well can cancel each other out. But I doubt it checks for this nonsense case, thats why I wrote "... **_effectively_** a null statement". It still is useless, such tasks are why people leave answering to the question to others. A practically usabel example would increase motivation. But as most teachers can't/don't really program themselves ... – too honest for this site Mar 02 '16 at 13:57
  • It is a question from an exam, they don't provide full answers and this way of using malloc seemed odd to me so I decided to ask about it. It's good to hear a confirmation that it is useless, I was rather confused as to why would anyone write such code anyway (now I understand it was just meant to confuse). – Anna Mar 02 '16 at 14:18

1 Answers1

0

The combined effect of the two loops seems to be to set m to n*n-1 The malloc then allocates that number of bytes and frees it. Hence the space complexity of O(n^2).

JeremyP
  • 84,577
  • 15
  • 123
  • 161