0

I have read the relevant problems about Unkonwn Behavoir.But I insist to ask WHY The following code:

#include <stdio.h>
int main(){
    char a[] ={'1','2','3',};
    // char *p = a;
    puts(a);
    return 0;
}

when I comment the char *p =a,it can output the correct answer 123.But when I uncomment this sentence,the output gives the 1239�( with some strange characters.What exactly is the cause of this problem?

Zhilai Liu
  • 13
  • 5
  • 1
    Im not sure what the problem is here. I was able to get the correct out of ```123``` with both the commented line and uncommented. – Joe Davis Nov 11 '20 at 14:16
  • 4
    The problem is the lack of null termination. The difference with or without `char* p` comes from [undefined behavior](https://software.codidact.com/questions/277486). Likely you alter the stack memory layout or similar. Maybe some zero ended up in memory after the characters by (bad) luck. – Lundin Nov 11 '20 at 14:17
  • 2
    I think, it's just the memory allocation algorithm of your operating system. In fact, there is no string terminating character at the end of the char array in either case; so, each should print garbage after '3' until `puts` comes across a `\0` (a zero byte). – ssd Nov 11 '20 at 14:18
  • When you write incorrect code, a bad outcome is not guaranteed, any more than you'll get arrested if you break a law - you might. Please see [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). – Weather Vane Nov 11 '20 at 16:14

0 Answers0