I wrote the following code for testing the functionality of malloc() .
The Code is compiled using GCC and executed with no errors.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
char *str;
str=(char*)malloc(4*sizeof(char));
printf("Enter string");
gets(str);
if(sizeof(str)>4*sizeof(char))
{printf("Out of Memory");
free(str);
str=NULL;
}
else{
printf("\nsring entered=\n");
while(*str)
{
printf("%c",*str);
str++;
}
free(str);
}
return 0;
}

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

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

sizeof(char)

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 .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.