c++ - Size of strcat Destination Array -
take following program:
#include <iostream> #include <cstring> using namespace std; int main() { char a[8] = "hello, "; char b[7] = "world!"; strcat(a, b); cout << a; return 0; } notice a , b have same size assigned strings.
the documentation states strcat(a, b) work, a needs large enough contain concatenated resulting string.
nevertheless, cout << a displays "hello, world!". entering undefined behavior?
"am entering undefined behavior?"
yes. region @ end of a[] has been written over. worked, time, might have belonged else.
here use struct control memory layout, , demonstrate it:
#include <iostream> #include <cstring> using namespace std; int main() { struct s { char a[8]; char b[5]; char c[7]; }; s s; strcpy( s.a , "hello, " ); strcpy( s.b , "foo!" ); strcpy( s.c , "world!" ); strcat(s.a, s.c); cout << s.a << endl; cout << s.b << endl; cin.get(); return 0; } this outputs:
hello, world! orld! instead of:
hello, world! foo! the strcat() has stomped on b[].
please note in real life example such bugs may far more subtle, , lead wondering why innocent function calls 250 lines later crash , burn horribly. ;-)
edit: may recommend use strcat_s, instead? or, better, std::strings:
#include <string> #include <iostream> using namespace std; int main() { string = "hello, "; string b = "world!"; = + b; cout << a; }
Comments
Post a Comment