I have a function as such:
int foo(void *val){
(char *)val="Long String";
return 0;
}
This function is called like:
char str[25];
foo(str);
printf("%s",str);
I get nothing printed out for some reason. what is wrong here?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You store the pointer to
"Long String"into a variablevalwhich is allocated on the stack. The lifetime of the variable extends only during the call tofoo().You don’t want to store the address to
"Long String"on the stack. You want to copy the string under the provided address.You should do this instead:
This isn’t safe, though. You should pass the maximum size of the buffer into
fooand usestrncpy()instead ofstrcpy().