Let's go at it line by line and see where it goes wrong:
int main(){
char * str = (char*)malloc((int)sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int));
str = "hello";
str2 = "hey jude";
copyStrings(str2, str);
free(str);
free(str2);
return 0;
}
int main(){
- this is an improper definition of main
. Should be int main(int argc, char **argv)
char * str = (char*)malloc((int)sizeof(double));
- defines str
, then allocates (probably) 8 bytes of memory and assigns its address to str
. malloc
takes a size_t
argument, so the cast (int)sizeof(double)
is incorrect. Also, in C the return value of malloc
should never be cast. So this line should be char * str = malloc(sizeof(double));
char * str2 = (char *)malloc((int)sizeof(int));
- all the same problems as the preceding line. Should be char *str2 = malloc(sizeof(int));
str = "hello";
- causes a memory leak, because the memory you JUST ALLOCATED two lines earlier is now irretrievably lost. You've got two options here - either don't allocate the memory when defining str
or free it first. Let's do the latter:
free(str);
str = "hello";
str2 = "hey jude";
- same problem, similar solution:
free(str2);
str2 = "hey jude";
copyStrings(str2, str);
- here you're telling your routine to copy the constant string "hello" over the top of the constant string "hey jude". This will work fine on some systems, but will blow up on other systems. The question is in the treatment of the constant string "hey jude". If it's stored in modifiable memory the code will work just fine. If it's stored in memory which is marked as being unmodifiable, however, it will blow up. It seems that the latter is the case on your system. To fix this you probably want to go back to the previous line and change it to
str2 = malloc(20);
That's more memory than you'll need, but it will work just fine.
free(str);
- you're attempting to free the constant string "hello", which is not dynamically allocated memory. This needed to be done prior to the assignment str = "hello";
.
free(str2;
- same problem as above. This needed to be done prior to the assignment str2 = "hey jude";
.
}
- correct
Best of luck.