Reputation: 165
Had a basic c++ question. I find char array not initialized are having length > 0. Can someone explain ?
#include <iostream>
int main() {
char test1[5];
test1[4] = 0;
printf("test1 array %s, length %d\n", test1, strlen(test1));
char test2[128];
test2[127] = 0;
printf("test2 array %s, length %d\n", test2, strlen(test2));
}
This prints (why empty and zero length for the first array and non-empty and non-zero length for the second array)?:
test1 array , length 0
test2 array 8??, length 6
Upvotes: 2
Views: 3084
Reputation: 2981
Standard C
strings end at a null-terminator, which your uninitialized data may or may not have anywhere in it. I think other answers have covered that already.
And while this may seem pedantic and you may already know it, the length of a char array is NOT the same as the length of the string of it contains (if it contains one). The output of sizeof()
on your variables is NOT undefined, because it doesn't look at the contents at all:
#include <string.h>
#include <iostream>
int main() {
char test1[5];
test1[4] = 0;
printf("test1 array %s, string length %d array length %d\n", test1, strlen(test1), sizeof(test1)/sizeof(char));
char test2[128];
test2[127] = 0;
printf("test2 array %s, string length %d array length %d\n", test2, strlen(test2), sizeof(test2)/sizeof(char));
}
Output:
test1 array , string length 0 array length 5
test2 array P`, string length 3 array length 128
One last note. NULL-terminated strings are problematic. Anytime you find yourself using them in C++
instead of std::string
you should be able to answer the question "why?" There are reasons....but you should have one.
Upvotes: 3
Reputation: 12174
The problem:
char test1[5]; // no initialization
test1[4] = 0; // this is assignment not initialization
As per dcl.init/12
When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced.
Thus, test1
has indeterminate value.
Using this variable in functions is undefined behavior.
Upvotes: 1
Reputation: 404
The initializing code 'test2[127] = 0;' is not correct. You should initialize the char array as following:
char test2[128]={0};
Or
char test2[128];
test2[0] = 0;
Upvotes: -1
Reputation: 211670
Since you haven't initialized those values you're getting undefined behaviour. That is they can contain anything. Maybe zeroes, maybe random data.
Passing an uninitialized character buffer to printf
is undefined behaviour and should not be done. That might work, it might not. The only way to get defined behaviour is to initialize it properly.
Upvotes: 4