I wrote the following code for testing the functionality of malloc() .
The Code is compiled using GCC and executed with no errors.
int main(void)
char *str;
printf("Enter string");
{printf("Out of Memory");
printf("\nsring entered=\n");
return 0;

As i run the above code prints string even greater than 4 bytes long . Please help me with my confusion.

6 Years
Discussion Span
Last Post by Banfa

OK to start with if you enter a string longer than 3 characters you overwrite the end of the allocated buffer. Writing outside the bounds of a valid object results in undefined behaviour. Once you have undefined behaviour anything may happen.

You should use the function fgets rather than gets because it prevents buffer over-run in this manner.

You problem lies in this line if(sizeof(str)>4*sizeof(char)) . sizeof(str) is almost certainly not doing what you thing it is. it returns the size in bytes of the object str. What is str? From you code it is a char* . In most cases on a 32bit system the size of a pointer is 4 bytes (and 8 on a 64bit system) so sizeof(str) is going to return 4, in fact this is calculated in the compiler because it is a value that is fixed at compile time.

The other half of the condition is also a constant that the compiler can calculate


is 1 (as defined by the standard) and the compiler knows this and can easily do the multiplication to get 4*sizeof(char)) is 4.

So your if statement is resolve by the compiler as if(sizeof(str)>4*sizeof(char)) equivalent to if(4>4) , and since 4 is not greater than 4 equivalent to if(0) . An optimising compiler will calculate this and it will not even put your error code into the program.

I suspect you indented to use the function strlen to get the number of characters in a string (as input by the user). But note if you do this you will be invoking undefined behaviour, the correct solution, as I said at the top, is to use fgets .

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.