Ad
  • Default User Avatar

    Ok, I got it now. I was awear of the stack variables, was a little confused about the moment the memory is set to "writable". I see now my problem. Thank you for pointing it out! Have a great day/night!

  • Custom User Avatar

    Yep my bad its in the Data/BSS Section. However my point is that using static will make it persist beyond the scope of the function call.

  • Custom User Avatar

    ... but static char returnString[20] = ""; is not allocated on a heap?

  • Custom User Avatar

    This is a stack variable
    char returnString[20] = "";

    When the function returns this memory allowed to be reused.
    You are now returning a pointer into unallocated memory.
    It just so happens that the OS has not reused it so you see what you expect, but its bad coding.

    If you use a HEAP allocated variable this problem is avoided.
    static char returnString[20] = "";

    However that is brittle too as your code is written such that large number could append data beyond the 20 bytes allocated. This would be a buffer overflow, you've heard about these, those "bugs" are used to breach security in systems.

    I'll also point out that using a HEAP variable would mean this code would not be pthread safe unless you used mutex's, but that's a conversation for another time.

    Examine my solution.

  • Default User Avatar

    Hello there,

    Can you elaborate? I am returning the created string, after that, even though the data from the string will be deleted (after the return statement), I will no longer use the pointer in the main program. What I envisioned this method to do is basically a 1-time call, when I would set the roman literals equivalent, after that using the saved main-local variable for further operations.

    Can you, please, tell me what would be the issue in that case? and how can I improve my code?

    Thank you for finding the time to look into my code.

  • Custom User Avatar

    You are returning the address of a stack variable. This is very bad.