Loading collection data...
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection.
snap !
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];
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.
I too struggled with this until I read the discourse chats. Look for highest 5-digit "string fragment". Think "sliding window" over the string.
Check my solution. It passes but its not what is expected due to a bug in the test harness.
Test case exploit. This is not what is expected.
I'm exploiting a defecting in your testing to pass this. I suggest you improve the test harness.
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.
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.
For large values of n you will you get a buffer overflow on result.
You are returning the address of a stack variable. This is very bad.
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.