title: Allocate memory and save string in c
body: <p>I was wondering why the following code isnt't working</p>
  
  <pre><code>int main(int argc, char **argv)
  {
       char *test = (char*) malloc(12*sizeof(char));
       test = "testingonly";
       free(test);
  }
  </code></pre>
  
  <p>After thinking about it my assumption was that first i allocate space for 12 chars in memory but the assignment in the next line creates a char array on the stack and the memory address of that is passed to test. So free() tries to release space on the stack which is not allowed. Is that correct?</p>
  
  <p>So what would be the correct approach to save a string on the heap? Is the following a common way?</p>
  
  <pre><code>int main(int argc, char **argv)
  {
       char *test = (char*) malloc(12*sizeof(char));
       strcpy(test, "testingonly");
       free(test);
  }
  </code></pre>