When writing some C code, I ran into a small problem when I had to convert a character to a "string" (the part of memory whose beginning is given by the char* pointer).
The idea is that if some sourcestr pointer (not NULL ) is set, I must use it as my "final string", otherwise I must convert the given charcode to the first character of another array, and use it instead.
For the purposes of this question, we will assume that the types of variables cannot be changed in advance. In other words, I cannot just save my charcode as const char* instead of int .
Since I tend to be lazy, I thought to myself: "Hey, could I just use the address of the character and treat this pointer as a string?". Here is a small snippet of what I wrote (has not yet hit my head against the wall!):
int charcode = FOO; char* sourcestr = "BAR"; char* sourcestr = NULL; char* finalstr = sourcestr ? sourcestr : (char*)&charcode;
Now, of course, I tried, and, as I expected, it works. Even with a few warning flags, the compiler is still happy. However, I have this strange feeling that this is actually undefined behavior, and that I simply shouldn't do that.
The reason I think so is because char* arrays must be terminated with a null character in order to print correctly as strings (and I want it to be!). However, I'm not sure if the value in &charcode + 1 will be zero, so I could get some buffer overflow madness.
Is there an actual reason why it works correctly, or was I just lucky to get zeros in the right places when I tried?
(Note that I am not looking for other ways to achieve the conversion. I could just use the variable char tmp[2] = {0} and put my character at index 0. I could also use something like sprintf or snprintf , with provided that Iβm careful enough with buffer overflows. There are many ways to do this, Iβm just interested in the behavior of this particular cast operation.)
Edit: I have seen several people call this hacker, and let it be clear: I completely agree with you. I don't have enough masochist to do this in the released code. This only makes me curious;)