#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv) {
char *p="Hello World";
int i,end;
char *copy_p = NULL;
printf("Before copy: %s\n",p);
copy_p=(char *)malloc((size_t)(strlen(p) + 1));
if(!copy_p) { //Hopefully the system can allocate 12 bytes, but for safety...
fprintf(stderr,"Could not allocate memory for copy_p, errno: %d\n",errno);
return 0;
}
strcpy(copy_p,p); //Only reason not to use strncpy is we just allocated
printf("After copy, before replace: %s\n",copy_p);
end=strlen(copy_p); //What is the length of the string literal changes?
for(i=0;i<end;i++) { //I just replaced the whole string. Your example would leave $$$$$$$$$$d\0 in the buffer, not sure what the intent was
copy_p[i] = '$'; //Let the compiler do the pointer arithmatic
}
printf("After replace: %s\n",copy_p);
return 1;
}