Reputation: 739
I was playing around with C and the scanf
function and came across this weird error that I can't seem to figure out. Given the following code:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a;
} sample;
void fn(sample *s) {
char command;
scanf("%[abc]", &command);
printf("Read: %c\n", command);
printf("In the sample function:, %i\n", s->a);
}
int main() {
sample *s = malloc(sizeof(sample));
s->a = 4;
printf("Before sample function: %i\n", s->a);
fn(s);
printf("After sample function: %i\n", s->a);
return 0;
}
It seems to seg fault. With the output:
$ ./sample
Before sample function: 4
a
Read: a
In the sample function:, 4
Segmentation fault (core dumped)
I used gdb and attached a watch
to the struct, it seems that inside the scanf
function, it seems to 'modify' the struct? Which is weird, because even after the scanf
inside the sample function 'fn
', it is able to print out the struct fields fine. However, once returning from the fn
and jumping back into main
, it seg faults when it tries to print out the same information?
Interestingly, if you change the scanf
to scanf("%c\n", &command);
(without the character set) it seems to work fine. For the record, the version of gcc I am using is 4.7.2, and I am compiling the code with: gcc -O0 -o sample sample.c
.
My only thought is that perhaps character sets aren't supported by gcc? I'm not sure. Just wondering if anyone else could clear this up?
Upvotes: 3
Views: 1452
Reputation: 145829
scanf("%[abc]", &command);
writes a string not a single character. The trailing null character of the string is being written in &command + 1
in your program.
You should pass to scanf
something like:
command
with command
being:
char command[2];
Upvotes: 6