Dear Guys,
I want somebody to explain this behaviour. I am using devC++ IDE and I had problem with the following code snippet. I rectified it, but i need to know the correct answer why its solved?.
I declared a temporary character pointer (tmp) in main and used it directly in strcpy function to copy contents of a string, str, that is
int main(){
char str[] = "I Want To Know";
char *tmp;
strcpy(tmp,str);
return 0;
}
The above code works fine. But when I tried to do the same in a function, I started getting run time error. The function is defined as follows:
void someStrFunc(const char *str){
char *tmp;
strcpy(tmp,str);
return;
}
However, this is solved by using the following code,
void someStrFunc(const char *str){
char *tmp;
tmp = (char*)malloc(sizeof(strlen(str)));
strcpy(tmp,str);
return;
}
I want to know why is it not required to allocate the memory for tmp in main() or other way, why is it required to allocate the memory for tmp in the function someStrFunc.
Regards,
V.Amar