-8

Consider the following C code snippet:

char *sentence = NULL;
strcpy(sentence, "Helloworld");
printf ("%s", sentence);

is the code segment correct or error? If correct what is the output?

a) Error

b) Helloworld

c) Null.Helloworld

d) None of the above

  • 1
    You have to allocate enough memory for `sentente`. Your code invokes undefined behavior. – kocica Jul 30 '18 at 10:08
  • 4
    It leads to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior), so *anything* could happen, including calling [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Some programmer dude Jul 30 '18 at 10:08
  • Perhaps you should have compile this code to know the answer? – danglingpointer Jul 30 '18 at 10:08
  • 1
    Picked up from some question paper? – babon Jul 30 '18 at 10:08
  • 1
    What do you think will happen when you put a string into a NULL pointer? This is a suicide behavior that should be avoided in any circumstances – edhu Jul 30 '18 at 10:09
  • 1
    "*Perhaps you should have compile this code to know the answer?*" <- for **undefined behavior**, I don't think this is the best advice ;) –  Jul 30 '18 at 10:11
  • 1
    Normally whenever you get some simple task as homework you are tought the topic before. Which part of your course material is unclear? – Gerhardh Jul 30 '18 at 10:11
  • @Felix Palmen too bad kernel memory segment is too far away and protected – edhu Jul 30 '18 at 10:15
  • Possible duplicate of [strcpy pass initialized null pointer c](https://stackoverflow.com/questions/38065778/strcpy-pass-initialized-null-pointer-c) – Tom Zych Jul 30 '18 at 10:15
  • Please read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Haem Jul 30 '18 at 10:42

1 Answers1

1

None and any. Dereferencing a nullpointer (and, copying data to it means it is dereferenced) is undefined behavior, there's nothing you can tell about the behavior of the program. A crash is of course very likely.

  • 2
    ..and equally unlikely. It can just behave as proper memory allocation would have been done. No guarantees, whatsoever. – Sourav Ghosh Jul 30 '18 at 10:10
  • With a nullpointer, it's much more likely to crash. Modern operating systems will catch that. But it's outside the scope of C anyways. –  Jul 30 '18 at 10:12
  • thanks for the help. I was also getting the same, undefined behavior as I executed this segment, but wasn't able to find the reason, which I got now. – Rudrankit Sharma Jul 30 '18 at 10:13
  • @BDH I'd (really) like to see a machine where a program with undefined behavior endangers your life ;) Well, as a programmer. –  Jul 30 '18 at 11:08
  • @Felix Palmen I guess an overflow in rocket launcher program will be a suitable candidate:) – edhu Jul 30 '18 at 13:01