#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char str[5]={'\0'};
printf("Initial length before passing = %ld\n",strlen(str));
input(str);
printf("Received string = %s\n",str);
printf("Length after getting input(calling function) = %ld\n",sizeof(str));
}
input(char * buffer)
{
puts("Enter something: ");
printf("Initial length after passing = %ld\n",strlen(buffer));
if ( fgets(buffer, sizeof(buffer), stdin) == NULL )
return -1;
else
{
printf("Length after getting input(called function)= %ld\n",strlen(buffer));
return 0;
}
}
Initial length before passing = 0
Enter something:
Initial length after passing = 0
hello
Length after getting input(called function)= 6
Received string = hello
Length after getting input(calling function) = 5
Initial length before passing = 0
Enter something:
Initial length after passing = 0
helloooooo
Length after getting input(called function)= 7
Received string = hellooo
Length after getting input(calling function) = 5
Why is it printing different lengths in when I gave different input?
1) In output 1 & 2 why the initial length is 6 when i allocated space for only 5 characters?
Your first strlen(str)
call isn't really even defined since you declared char str[5]
but didn't put anything into it. So the contents are who-knows-what. That fact that strlen(str)
returned a 6 just means that there happened to be 6 non-zero characters in memory, starting at address str
before it encountered a 0.
2) why the length of string is different before passing and after passing in both output 1 and output 2?
After getting a length of 6 for random memory contents, you loaded something into the string buffer and zero terminated it. So the length changed to something real.
3) In output 2 why "Length after getting input(called function)= 7" when i allocated only less space?
Because you actually overran your allocated space with a longer string (of length 7). You were lucky the program didn't crash in that case.
When you declare a buffer in C, such as:
char str[5];
All it does is tell the compiler you're reserving 5 bytes of space to do something and it entitles you to use that space and only that space for str
. It doesn't necessarily have anything in the buffer to start unless you put something there, and it doesn't prevent you from writing more than you declared.
Note that str[5]
isn't big enough to hold "hello" since strings in C are zero-terminated. So you need a character buffer of size N+1 to hold a string of size N. When you overflow buffers in C, your results will become erratic and unpredictable.