program-1 ->
#include <iostream>
#include <cstring>
int main()
{
char a[4];
memset(a, 'A', sizeof a);
std::cout << a << '!';
return 0;
}
program-1 outputs what I expected AAAA!
But as soon as I introduce another string (char array), things change!
program-2 ->
#include <iostream>
#include <cstring>
int main()
{
char a[4], b[4];
memset(a, 'A', sizeof a);
memset(b, 'B', sizeof b);
std::cout << a << '!';
std::cout << ' ' << b << '?';
return 0;
}
program-2 outputs AAAABBBB? BBBB?
AAAABBBB? BBBB?
. That means, here a
is AAAABBBB
But I declared the length as 4? So what is going on? Does memset change the array length when another array is memset
or something?!
My build line is g++ -Wall -Wextra -std=c++17 main.cpp -o main
Does memset change the array length
No. Memset does not change the array length. In fact the length of any array never changes through the lifetime of the array.
So what is going on?
The stream insertion operator that you use has the pre condition that the string must be null terminated. Violating pre conditions results in undefined behaviour.
You insert non-null terminated strings into the character stream. This violates the pre condition and the behaviour of the program is undefined.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.