0

I am studying max heap and in it there is a createheap function. In it , there is a for loop like this

    for (i = 0; i < capacity; i++) {
        h->arr[i] = nums[i];
    }

if size of nums is not equal to capacity then does the variable i gives the size of nums or is it equal to capacity? (the for loop runs till i is equal to capacity ,right?)

  • You really need to tag questions with the relevant programming language. Assuming that this is C code, the size of `nums` is not being considered; if `capacity` is larger than the size, garbage will be read from memory past the end of the array. Other languages might throw an exception once `i` goes out of range. – jasonharper Aug 24 '23 at 04:16
  • @jasonharper My doubt is if size of nums is less than the size of capacity then, does for loop runs till i is equal to capacity or not – Uday_singulariy Aug 24 '23 at 04:22
  • 2
    Why would it stop any earlier? The loop has no stopping condition that has anything to do with `nums`. Of course, the whole program might crash once you start accessing memory beyond the actual end of the array. – jasonharper Aug 24 '23 at 04:28

1 Answers1

0

...the for loop runs till i is equal to capacity ,right?

~~No.~~ Maybe.

When capacity exceeds "the size of nums", once i is equal to "the size of nums", further iterations lead to undefined behavior (UB). Anything may happen, including executing until i == capacity, crashing due to accessing memory it doesn't own, replacing your hotel with a football stadium, etc.

yano
  • 4,827
  • 2
  • 23
  • 35
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256