6

Why does this simply c program segfault when I call printf?

#include<stdio.h>
int main() {
        char* f;
        char* b;
        *f = 'x';
        b = f;
        *b = 'y';
        printf("%c", *f);
}

I'd expect 'y' to be printed. I dereference f to obtain the character, right?

John Hoffman
  • 17,857
  • 20
  • 58
  • 81
  • 6
    I see that you're getting some downvotes, and I wouldn't be surprised if there's a duplicate somewhere, but **thank you** for providing complete working code that reproduces the issue, and for clearly stating the expected results. (Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. Include attempted solutions, why they didn't work, and the expected results.) You've done these things. I think that, as @tkcsam said, it's a valid question, and you've asked it well. – Joshua Taylor Oct 08 '13 at 19:52
  • 1
    @tkcsam Because if someone doesn't even bother reading through the tutorial attentively enough to notice such a blatant mistake (nor does he search the site for an obvious duplicate), that by all means deserves a couple of downvotes. The dupe I linked to is literally the first google hit for "pointer dereference segfault". –  Oct 08 '13 at 19:55
  • Why are we using a *C++* question as a dup of a *C* question, [we should not be doing this](http://meta.stackexchange.com/questions/195292/should-we-discourage-marking-c-and-c-questions-as-duplicates-of-each-other-and). – Shafik Yaghmour Oct 08 '13 at 20:09

0 Answers0