0

I just want to verify I got this right. The copy from sr to ds2 gives an error. Is this because ds2 is considered "const"?? Thanks and hope this isn't a bore.

#include <stdio.h>
#include <string.h>
#include <malloc.h>

int main(void)
{
    char *sr = "Hello World";
    char *ds1 = (char*)malloc(100 * sizeof(char));
    char *ds2 = "12345678901234567890";

    // This statement works just fine
    printf("%s\n", strcpy(ds1, sr));

    // This gives error
    strcpy(ds2, sr);


    printf("%s\n", ds2);

    return 0;
}

1 Answers1

0

Here is a similar post

difference between char* and char[] with strcpy()

When you do this

char *ds2 = "12345678901234567890";

the compiler leaves the pointer pointing to a non-writable memory region.

With this line

// This gives error
   strcpy(ds2, sr);

You are trying to do an strcpy into the non-writable memory.

You should also have a free for each malloc as you are allocating memory but not de-allocating it.

Community
  • 1
  • 1
kmcnamee
  • 5,097
  • 2
  • 25
  • 36
  • Excellent - thought something like that. Yes, I know I should have a free(). (Trying to get back on the horse after 25yrs off).I appreciate your time and assistance. Best. – Panchdara Mar 11 '15 at 23:52