Ad
  • Custom User Avatar
  • Custom User Avatar

    Correct is never best practice to return a stack allocated variable.

    This will fix it, that is unless you are threaded - as this isn't thread safe.
    static int newArray[length];

  • Custom User Avatar

    Allocating 500 bytes of memory and hoping for the best is not a good idea. As a buffer overflow will crash the code.
    If you don't know how much memory you'll need you should realloc as you go, only returning as much as required and no more.

  • Custom User Avatar

    I too struggled with this until I read the discourse chats. Look for highest 5-digit "string fragment". Think "sliding window" over the string.

  • Custom User Avatar

    Check my solution. It passes but its not what is expected due to a bug in the test harness.

  • Custom User Avatar

    Test case exploit. This is not what is expected.

  • Custom User Avatar

    I'm exploiting a defecting in your testing to pass this. I suggest you improve the test harness.

  • 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

    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.

  • Custom User Avatar

    For large values of n you will you get a buffer overflow on result.

  • Custom User Avatar

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

  • Custom User Avatar

    Two words; Buffer overflow.
    So many solutions suffer from this problem; allocating a buffer that should be big enough.
    Memory management in C is an important part of the solution.