0

I have following C code:

char* ToHex(char input)
{
    char output[3];
    char* HexArray = "0123456789ABCDEF";
    output[0] = HexArray[(input / 16)];
    output[1] = HexArray[input % 16];
    output[2] = '\0';
    return output;
}

void main()
{
    char* ptr = ToHex('a');
    char string[20];
    strcpy_s(string, 20, ptr);
    printf(string);
}

I'm trying to make a function that converts chars to hex.

Function works great and when debugging in Visual C ptr == "61".

Then when printing pointer I get: "¹⌂".

Now if I copy ptr into string and then print string, I see the expected "61".

Can anyone tell me what is going on?

How can I make it so whatever is returned by ToHex is properly printed?


Edit: made it work by using char *output = malloc(3), though I still don't understand the gist of local scope.

I get the var stops existing, but why did it print the correct output when copying outside of the local scope?

Jabberwocky
  • 45,262
  • 17
  • 54
  • 100
  • 1
    The array `output` is local to the function `ToHex()`. It ceases to exist immediatley after the `return` so your `main()` function receives an invalid pointer in `ptr`. – pmg May 10 '22 at 09:02
  • 1
    Does this answer your question? [error: function returns address of local variable](https://stackoverflow.com/questions/12380758/error-function-returns-address-of-local-variable) – Kenny May 10 '22 at 09:05
  • 1
    Decent beginner-level C books typically mention why you shouldn't return pointers to local data from functions. Solve this by doing caller allocation instead and pass the buffer as a parameter to the function. – Lundin May 10 '22 at 09:07
  • 1
    Hint: You're seeing _undefined behaviour_ here. Google that term. – Jabberwocky May 10 '22 at 09:24
  • The easiest fix for this case would be to return value of type `struct HexStr8 { char str[3]; }` (or, while you'r at it, make `str` big enough to hold 16, 32 or 64 bit number in hex). – hyde May 10 '22 at 09:32
  • 1
    Comment after your edit: it's undefined behaviour. Undefined behaviour includes _"apparently working fine"_. When it "appears to work" with copying the string, it's only because coincidentally the local variable which has gone out of scope has not yet been overwritten. – Jabberwocky May 10 '22 at 09:33
  • Hint: when you use `char *output = malloc(3);` don't forget to `free(ptr)` in `main` once you're done with it. – Jabberwocky May 10 '22 at 09:36
  • 1
    The correct term in this instance is "lifetime" not "scope" (though the "lifetime" and "scope" of `output` is the same). – pmg May 10 '22 at 09:41

0 Answers0