title: Leetcode : AddressSanitizer heap-buffer-overflow
body: <p>I am practicing the Leetcode question "Next Greater Node in Linked List" 
  and here is my code:</p>
  
  <pre><code>#define STACK_SIZE (10000U)
  
  typedef struct ListNode Node;
  
  static int stack[STACK_SIZE];
  static int top=-1;
  
  bool isEmpty()
  {
      return (top==-1);
  }
  
  void addToStack(int element)
  {
      stack[++top]=element;
  }
  
  void remFromStack()
  {
      --top;    
  }
  
  int getStackTop()
  {
      return stack[top];
  }
  
   typedef struct ListNode Node;
  
   int* nextLargerNodes(struct ListNode* head, int* returnSize) {
  
          if (head == NULL) {
  
              *returnSize = 0;
              return NULL;
          }
  
          int len = 0;
          Node *temp = head;
  
          while (temp) {
              len++;
              temp = temp-&gt;next;
          }
  
          if (len &gt; 0) {
              int *result = malloc(len * sizeof(int));
              *returnSize = len;
  
              if (result == NULL) {
                  return NULL;
              }
  
              int j = 0;
              while (j &lt; len) {
                  result[j++] = 0;
              }
  
              temp = head;
              addToStack(temp-&gt;val);
              j = 0;
              while (temp-&gt;next) {
                  temp = temp-&gt;next;
                  j++;
  
                  if (getStackTop() &gt; temp-&gt;val) {
                      addToStack(temp-&gt;val);
                  } else {
                      int i = 0;
                      while (!isEmpty()) {
                          i++;
                          result[j - i] = temp-&gt;val;
                          remFromStack();
                      }
                      addToStack(temp-&gt;val);
                  }
              }
              return result;
          } else {
              return NULL;
          }
  
  }
  </code></pre>
  
  <p>And I am getting the following error:</p>
  
  <pre><code>=================================================================
  ==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6030000
  WRITE of size 4 at 0x60300000000c thread T0
   #2 0x7f55143382e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.s
  0x60300000000c is located 4 bytes to the left of 20-byte region [0x60300
  allocated by thread T0 here:
   #0 0x7f55157c22b0 in malloc (/usr/local/lib64/libasan.so.5+0xe82b0)
   #3 0x7f55143382e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.s
  </code></pre>
  
  <p>I am not sure what's wrong here.</p>
  
  <p>Tried making sure all the code is correct, and when I test the code against my own test cases, it works perfectly fine, but when I submit the code, only then I am getting this error.  </p>
  
  <p>Note: The returned array must be malloced, assume caller calls free().  </p>
  
  <p>The utility functions dont have any malloc/ calloc called in them, so, that removes them from the equation.</p>