+ 3
Why does this produce weird output ??
12 Réponses
+ 5
Short answer: ptr=&sptr should be ptr = sptr;
Long answer:
By doing &sptr you get the address of the pointer itself, not the address where it is pointing to.
This value is an int ( an address is just an int ) and is incorrectly interpreted as a string.
How does this produce the weird output?
Well, you need to know a bit how a string in gcc works.
A string in gcc exists out of 3 important variables.
The 1st variable is a pointer to an array.
The 2nd variable contains the size of the array
The 3rd variable contains the capacity of the allocated array.
Gcc also uses a small string optimization, "Hello world" is small enough to trigger this in which case the 3rd variable becomes an array containing this small string instead.
Currently in memory it looks like:
Variable : [ Value in memory ]
sptr : [ 16 254 34 0 0 0 0 0 ]
word : [ 32 254 34 0 0 0 0 0 ] [ 11 0 0 0 0 0 0 0 ] [ 72 101 108 108 111 32 119 111 114 108 100 ]
Since sptr is interpreted as a string the internal string's memory looks like:
The printed string : [ 16 254 34 0 0 0 0 0 ][ 32 254 34 0 0 0 0 0 ] [ 11 0 0 0 0 0 0 0 ]
Internally the string detects that it is not using a small string optimization and starts reading from the 1st variable, which is a pointer and you might have guessed it, the 2nd variable is going to be how much it's going to read.
[ 32 254 34 0 0 0 0 0 ] = 2293280 characters.
Which explains the huge lap of text that shows up.
Next up, the program crashes because it either tries to access unallocated data or it tries to delete something that hasn't been allocated on the heap.
+ 3
It prints about 40-50 lines of wierd text (there is lot of computer info such as CPU type), then time limit exceeded.
+ 3
Try more times, it sometimes work sometimes not
+ 2
You mean time limit exceeded? This means it took too long, so SoloLearn stopped the program
+ 2
Oh yeah, it didn't output all that stuff last time
+ 2
Yeah, it's worked now
+ 2
So?
+ 2
It's a load of stuff about the CPU, and then the time limit is exceeded
+ 2
Yeah, what does it mean and why it shows?
+ 2
XD
+ 2
I don't know, I'm not really a pro at pointers :D
+ 1
Well that sorts it out :)