I’m playing with C and I’ve run into this error:
#include <stdio.h>
int main ()
{
char* foo;
scanf("%s", foo);
printf("entered %s", foo);
return 0;
}
scanf takes pointer, foo is pointer, yet I get bus error. How can I make it work?
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 never initialize
foo, so it points to a more or less random location in memory. Either allocate it on the stack.Or malloc it on the heap:
But if you malloc, don’t forget to free().
And watch out for buffer overflows; if something takes in a buffer but no maximum size, be very careful. You can specify a maximum length for
scanfby doing%9s, for instance.scanfwill not account for the terminating null, though, so you need to pass one less than the length of your buffer.