The following results cause garbled characters.
#include<stdio.h>
# include <stdlib.h>
# include <string.h>
int main() {
char*in="abc";
char*out;
while(*out++=*in++);
printf("%s\n", out);
return1;
}
There are two problems.
Problem 1 reserves memory and sets its address to out
.
Example:
char buf[10];
out = buf;
Issue 2 passes the first address of memory to printf
when viewing.
Example:
printf("%s\n", buf);
As for the corrective method, Soramimi has answered, I will explain what is going on.
Initial State
'a', 'b', 'c', '\0'
↑ point to the beginning of in "abc"
↑ out Uninitialized so it is uncertain where it is pointing
while(*out++=*in++);
On the first lap, a
has been written, so while
continues the loop
'a', 'b', 'c', '\0'
↑ in
'a'
↑ out
while(*out++=*in++);
Second lap, b
, so continue the while
loop
'a', 'b', 'c', '\0'
↑ in
'a', 'b'
↑ out
while(*out++=*in++);
On the third lap, c
has been written, so while
continues the loop
'a', 'b', 'c', '\0'
↑ in
'a', 'b', 'c'
↑ out
while(*out++=*in++);
On the fourth lap, \0
has been written, so while
end the loop
'a', 'b', 'c', '\0'
↑ in
'a', 'b', 'c', '\0'
↑ out
Run printf("%s\n", out);
in this state, so print the part of memory that you don't know where it is pointing yet.
Therefore, it is completely uncertain what will be output.Of course, character corruption is nothing but a program bug.
© 2024 OneMinuteCode. All rights reserved.