c++ - memory allocation details using strcat -
i'm using following code print strings.
#include<bits/stdc++.h> using namespace std; int main(){ char s[100]; while(1){ char f[10000]; cin>>s; strcat(f,s); cout<<f<<endl; } return 0; }
in each iteration new allocation of f character array done.
input
a b c d
i expected output this:
a b c d
but actual output is:
a ab abc abcd
why happening ? though i'm declaring new array in each iteration why kind of output ??
because: undefined behavior.
you not initializing array. you're declaring it. because declare
char f[10000];
does not mean it's going initialized empty array, automatically.
so, declared array, containing random data.
at point, cannot expect predictable behavior. results got 1 plausible outcome. not one.
edit: each time around loop, array ends @ same place on stack. first time in, operating system set new page, stack, cleared 0. strcat()ed string it. next time around loop, old data, previous iteration, still there. so, strcat() more stuff, appending end.
Comments
Post a Comment