-3

I am trying to read a string from a keyboard and store it in a character pointer. But it doesn't seem to work. Can someone please help me out. Here is the code.

char *city = "Bangalore";
char *state;
state = city;

printf("Enter your state : ");
scanf("%s",state);   // I get Bad access here.

but doesn't crash when I use this.

char city[] = "Bangalore";
char *state = city;
printf("Enter your state : ");
scanf("%s",state);
Preetham Baliga
  • 271
  • 2
  • 4
  • 15
  • you need to allocate memory in order to write into it with any predictable behaviour – amdixon Sep 05 '15 at 09:20
  • but state is pointing to city right ? So it has a memory location and is not a dangling pointer – Preetham Baliga Sep 05 '15 at 09:23
  • 4
    city is a constant string that you can't overwrite. see [why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-constant](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha). to fix just allocate state either on the stack or the heap before writing to it – amdixon Sep 05 '15 at 09:23

2 Answers2

1

You don't have memory allocated to store the state name so when you try to write in str you get BAD_ACCESS error. You should fix your program as below (assuming max name length is 256). This will eat 256 bytes out of your stack though.

int main() {
  char state[256];

  printf("Enter your state : ");
  scanf("%s",state);
  return 0;
} 

The assignment(state = city;) operator works because you are assigning one pointer value to another pointer i.e. only the address stored in city is copied to state.

kd84
  • 111
  • 3
0

There are two different ways of allocating memory for a string:

  1. char *str = "Some string"; This is located in a non-writable location.
  2. char str[] = "Some string"; This is located on the stack, thus is writable.

Because you are trying to pass a pointer to a non-writable location, which is then written to, you get the error. If you want your string to be mutable you need to allocate memory on the stack or heap. Anyone would probably allocate on the stack like kd84 suggested:

char state[256]; // take any size, that is reasonably high here
qwertz
  • 14,614
  • 10
  • 34
  • 46