strlen()

Hi friends -

1
2
3
4
5
6
 	char* ptr_temp = new char[1];
	char temp[1];

	printf("\nptr_temp size %d",strlen(ptr_temp));    //16
	printf("\ntemp size %d",strlen(temp));           //12


Why this is the output put?
May be because of padding but why exactly I really confused.
Please can any one help me clear it?

Note:- I am trying this on VS2010 - 32-bit
Both pointers point to junk data, so those results are where strlen happens reaches a zero.
In both cases you have uninitialised data.

Since a c-string is a null terminated array of characters, the last character of the array must be set to zero, in order to mark the end of the string. Thus the only valid string contained in an array of just one element must be an empty string, of length zero.

Because the data has not been initialised, it contains some garbage value. The strlen function simply searches each successive byte until it finds a zero. Of course by then it will be accessing some other memory which is beyond the end of the array.
1
2
3
4
5
    char* ptr_temp = new char[1];
    char temp[1];
	
    ptr_temp[0] = 0; // put terminating zero in last byte of array
    temp[0]     = 0; // put terminating zero in last byte of array 


Another example:
1
2
3
4
	char temp[4] = { 'c', 'a', 't', 0};
	
	printf("\ntemp size %d",strlen(temp));          
	printf("\ntemp contains %s", temp);

temp size 3
temp contains cat
Last edited on
Topic archived. No new replies allowed.