title: Heap Corruption Detected in Visual Studio, but program runs fine in another C compiler: why?
body: <p>I tried searching for this problem, and couldn't find any answers.  I wrote a program that implements a stack, and its operations, with linked lists.  The program compiles and runs perfectly on a C Web IDE. </p>
  
  <p>When I run the program in Visual Studio, it fails and gives me the following error:</p>
  
  <p>Debug Error!
  Program: C:\Users... my file path
  HEAP CORRUPTION DETECTED: after Normal block (#78) at 0x011058C8.
  CRT detected that the application wrote to memory after end of heap buffer.</p>
  
  <p>As my code runs fine elsewhere, this must be some issue with how I am using Visual Studio.  Any ideas?  I am new to Visual Studio, and am afraid this might be something stupid, but I can't seem to figure it out.</p>
  
  <p>I have included my code below, note that the failure is caused by the pop() function in Visual Studio.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  struct Node {
      int data;
      struct Node* next;
  };
  
  struct Node* top = NULL; //initialize head
  
  void push(int x);
  void push(int x) {
      struct Node* add = (struct Node*)malloc(sizeof(struct Node*));
      add-&gt;data = x;
      add-&gt;next = top; //make add point to what top (head) points to (old 1st)
      top = add; //make top point to add (new 1st)
  }
  
  void pop();
  void pop() {
      if (top == NULL) return;
      struct Node* temp = top;
      top = top-&gt;next;
      free(temp);
  }
  
  int topp();
  int topp() {
      return top-&gt;data;
  }
  
  int exist();
  int exist() {
      if (top-&gt;next) {
          return 1;
      }
      else {
          return 0;
      }
  }
  
  void PrintIt();
  void PrintIt() {
      struct Node* temp = top;
      while (temp!= NULL) {
          printf("%d ", temp-&gt;data);
          temp = temp-&gt;next;
      }
      printf("\n");
  }
  
  int main() {
      push(1); PrintIt();
      push(44); PrintIt();
      push(23); PrintIt();
      pop(); PrintIt();
      push(9); PrintIt();
      return 0;
  }
  </code></pre>