given the following code in C:
char str[] = "";
size_t size = strlen(str) + 1;
char *actual = memset(malloc(size), '@', size);
After I run this, actual = "@" .
If malloc assigns only 1 byte for actual variable,
how can it initialize it with '@' , which requires 2 bytes(because of the null char)?
Thanx
I tried to run the code and I thought it would raise an error but it didn't.
The post contains no support for this assertion. Possibly you added
printf("%s\n", actual);in the code, and the program printed “@”. That does not mean thememsetput a null byte after the'@'.char *actual = memset(malloc(size), '@', size);allocates one byte and sets it to'@'. It does not control what value appears the byte after that or even that there is any memory mapped at that address.It is possible there is a byte in memory after the
'@'that contains the value zero, and thatprintflooked at the memory whereactualpoints and found the'@'and the null byte and printed the'@'. It is even likely this is the case because this probably was the only code in your program, so nothing had used much memory yet, so there was a zero in memory after the'@'simply because it had been initialized to zero by the operating system and not changed by your program. However, this is not behavior you can rely on. The byte after the'@'could contain a different value, andprintfwould behave differently.Additionally, because the behavior in this situation is not defined by the C standard, optimization by the compiler could transform your program in ways you may find surprising. For example, it would be conforming to the C standard for the compiler to determine the behavior is not defined, so that all of the code in your program could be eliminated.