title: C Access Violation error
body: <p>When I try to execute the following code in Visual Studio I get a data access error. I looked it up but saw that it happens when I try to modify a string literal which is a read only.</p>
  
  <pre><code>char *my_strcpy(char *dest, const char *source)
  {
      int i;
      while(*dest)
      {
          *dest++ = *source++;
      }
      return dest;
  }
  
   int main()
   {
      char str[80] = "Hello, there!";
      char *strPtr = NULL;
  
      my_strcpy (strPtr, str);    
  
      return 0;
  }
  
  error:
  Unhandled exception at 0x01163C91 in PtrStrArr.exe: 0xC0000005: Access violation reading location 0x00000000.
  </code></pre>
  
  <p>I am unable to identify where I am modifying a string literal. I even declared the array as a constant. If I remove the declaration </p>
  
  <pre><code>  char *strPtr = NULL;
  </code></pre>
  
  <p>I get an error</p>
  
  <pre><code>Run-Time Check Failure #3 - The variable 'strPtr' is being used without being initialized.
  </code></pre>
  
  <p>Could you please point me to my mistake here?</p>
  
  <p>EDIT:</p>
  
  <p>Thanks to all the answers I was able to correct my code and get the ouput as below.</p>
  
  <pre><code> #include &lt;stdio.h&gt;
   #include&lt;malloc.h&gt;
  
   char *my_strcpy(char *dest, const char *source)
   {
      char *retVal = dest;
      int i=0;
      while(*source != '\0')
      {
          *dest++ = *source++;
      }
      *dest++ = '\0';
      return retVal;
    }
  
    void print_array(char *str)
    {
      int i;
      while(*str)
      {
          printf("%c",*str++);
      }
    }
  
    int main()
    {
      char str[80] = "What up dude?";
      char* strPtr;
      strPtr = (char *)(malloc(sizeof str));
      print_array (str);
      printf("\n");
      my_strcpy (strPtr, str);    
      print_array (strPtr);
      return 0;
    }
  </code></pre>
  
  <p>I do have one question though. In all your answers you have not made the cast from void* to char* when using malloc. But when I tried it out I had to explicitly</p>
  
  <pre><code>strPtr = (char *)(malloc(sizeof str));
  </code></pre>
  
  <p>I am using malloc in the right way?
  Thanks to every one for your answers.</p>