title: Segmentation fault when trying to free memory
body: <p>I have below code where I have commented when I get segmentation fault and when not.</p>
  
  <p>Originally I got segmentation fault and then I could figure out that probably I cannot initialize my char pointer locations like <code>"abcd"</code>. But I am not able to understand - WHY?</p>
  
  <p>I thought <code>testString = "abcd";</code> will put <code>a</code> at first memory address, <code>b</code> at second and so on ...</p>
  
  <p>Segmentation fault occurs when trying to free memory, based on how I initialize memory location.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void)
  {
      char* testString = malloc(sizeof(char) * 5);
  
      printf("Size of char is: %d\n", sizeof(char));
      printf("Size of int is: %d\n", sizeof(int));
  
      for(int i = 0; i &lt; 5; i++)
      {
          printf("Pointer addresses are: %p\n", testString + i);
      }
  
      char* tempPtr = testString + 2;
      printf("My temp pointer address = %p\n", tempPtr);
  
      // This gives me segmentation fault ....
      testString = "abcd";
  
      // This will not give me segmentation fault ....    
      //int count = 65;
      //for(int i = 0; i &lt; 5; i++)
      //{
      //    testString[i] = count + i;
      //}
  
      printf("Printing character...\n");
  
      for(int i = 0; i &lt; 5; i++)
      {
          printf("Characters are: %c\n", testString[i]);
      }
  
      printf("Freeing memory...\n");
      free(testString);
  
      //printf("Access after freeing &gt;&gt;%c&lt;&lt;\n", tempPtr[0]);
      //free(testString);
  }
  </code></pre>
  
  <p><hr></p>
  
  <p>Based on @M.M. and @Jonathan's comment I understood that with <code>testString = "abcd";</code> my <code>testString</code> will point to a memory location where string "abcd" was created and since I didn't malloc'ed it I cannot free it. Also, since my original pointer to heap memory (which I got using malloc) is gone, so it is waste of memory or memory lead. </p>
  
  <p>So, does it means that when I use printf statement like <code>printf("Printing character...\n");</code>, this is also a memory leak? Then how do I avoid it? Looping and inserting into char* is certainly a bad idea.</p>