In this program function parameter is an array of characters(string). In this code the size of function parameter is 20 bytes and the size of local variables in function is only 4 bytes. Please explain why this happens why the size of local variable is only 4 bytes why not less or more why buffer overflow does not happens Code: /* * Sample Code to demonstrate the size of different variables * * By Ranjith Sutari, 2007 */ #include<stdio.h> /*Function to Read the String * the size of the local variable in this function is only 4 bytes */ int read_string(char prompt[], char answer[], int max) { fputs(prompt, stdout); fflush(stdin); fgets(answer, max, stdin); printf("size of the local variable answer in function read_string is %d\n", sizeof answer); return 0; } /* Function to print the string * the size of the local variable in this function is 4 bytes only */ int print_string(char prompt[], char answer[]) { fputs(prompt, stdout); printf("%s", answer); printf("Size of the local variable answer in function print_string is %d", sizeof answer); return 0; } int main() { char STRING[20]; /*size of the STRING is 20 bytes */ printf("Size of The variable string in function main at beginning is %d\n\n", sizeof string); read_string("What is your Name : ", STRING, sizeof STRING); /* STRING IS PASSED AS FUNCTION PARAMETER*/ print_string("Your name is ", string); /* size of the string is 20 bytes*/ printf("\n\nSize of The variable string in function main at end is %d\n", sizeof string); fflush(stdin); getchar(); return 0; } Thanks in Advance Ranjith Sutari
First off, fflush(stdin) is undefined. Flushing a stream is only valid for output streams, or update streams when the last operation was a write. http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1052863818&id=1043284351 As for your main question, the sizeof is applied to the parameter value (in this case, a pointer). The sizeof operator can't work out how much data a pointer points to (see example). Using [ ] instead of pointer notation in your function declaration doesn't change anything. Eg. Code: void foo ( const char *a ) { printf("%lu\n", sizeof(a) ); } int main ( ) { char a[] = "hello"; char b[] = "this is a longer string"; foo(a); foo(b); return 0; } Also see http://c-faq.com/aryptr/aryparmsize.html