03
Aug
08

On Stack :: Starzan and Cheetae Question

Rommel-kun: char Starzan[strlen(Cheetae)];
Rommel-kun: bossing do you remember our conversation regarding the above code?
Rommel-kun: What is the weakness of the above code?
GovZ Repuspolo: ok game .. in your opinion what is its weakness …
Rommel-kun: hmm …it is possible to fail if the string is empty…
Rommel-kun: zero…
Rommel-kun: ahhh
Rommel-kun: wait i will verify with msdn ….
GovZ Repuspolo: hahahahah
Rommel-kun: there it is!
Rommel-kun: strlen will return -1 if string contains invalid char
Rommel-kun: haha
Rommel-kun: is that the one?
GovZ Repuspolo: hahahah partially correct
Rommel-kun: partially? hahahaha it is like a new puzzle
GovZ Repuspolo: ok let us try to share the answer on your question …
GovZ Repuspolo: i will answer via my blog site …
Rommel-kun: thanks
GovZ Repuspolo: no problem

For everyone to understand, alwyn, rommel and I had dinner one time and i told them how i hated malloc, calloc and realloc. And as far as I can, I try to stay away from them, for reasons I will disclose further blogs. But for now, please accept the fact I hate the three commands.

In my avoidance of malloc() or any of its forms, I ended up using the following kind of technique :
==============================
/* C++ int32 = 32bit integer int8 = char */
int32 vic_sotto(0);
vic_sotto = function_that_returns_int32(2,5);
int8 jimmy_santos[vic_sotto + 1];
==============================
Assuming the above code is valid according to the coding guidelines, there is an innate flaw to the code. But first let me get back to rommel’s responses …

1. Rommel-kun: wait i will verify with msdn ….

-> 20 Points for attitude : ANY DEVELOPER SHOULD ALWAYS CHECK HIS OR HER PLATFORMS AUTHORITATIVE MANUAL … hmmm though this may be overkill, it is imperative, we check what we do not know. Especially windows implementations :) (i have so many stories about windows interoperability… hahahah i can write a document about it. nahhh … not my style :) )

2. Rommel-kun: strlen will return -1 if string contains invalid char

-> 10 points for attitude : Be patient until one finds an authoritative answer for a simple or complex question. In my experience though, most of the times the answer will elude you depending on the question’s level of difficulty.

However, as I have said, the answer is partially correct. In an embedded platform, and or in Windows for that matter, one should always think that any form of used resource has a limit. In this case, the STACK IS NOT INFINITE, NOTHING IS INFINITE. So therefore, aside from having a negative sized allocation, you may end up with something like :

==============================
/* C++ int32 = 32bit integer int8 = char */
int32 vic_sotto(0);
vic_sotto = function_that_returns_int32(2000000,50000000);
/* vic_sotto = 2,000,000,000 */
int8 jimmy_santos[vic_sotto + 1];
==============================

Now what do you think will happen? This is what I call stack failure (stack overflow). You see for each process ( or thread or task) we create, the OS allocates a defined size for its stack. (As for the idea of stack, check wiki for it :) ) This is where your local variables are stored temporarily. Once the function exits, (or thread/process/task for that matter) it releases the used memory.

The stack is the best place to get memory from, and the fastest. But in my experience it can be really really small in terms of size. For example, in one of the non-RTOS I have worked on, the stack size was only 8Kb. In one of my RTOS adventures, I came across a 2K byte stack. So whether you are in windows or not, or you have a hell of a freeway for stack … DONT ABUSE YOUR RESOURCES… its much like life too, never abuse your resources in life. :)

So to correct the above code, assuming we still want to do it the same way :
==============================
/* C++ int32 = 32bit integer int8 = char */
int32 vic_sotto(0);
vic_sotto = function_that_returns_int32(2000000,50000000);
/* guard the damn thing with a macro JOEY_DE_LEON = 20 */
if ((vic_sotto<0) || (vic_sotto + 1 > JOEY_DE_LEON)) {
return -1; /* function failure */
}
int8 jimmy_santos[vic_sotto + 1];
==============================

Remember :
1. When you can, if it is ok, use STACK.
2. The STACK is NEVER INFINITE.
3. Apply a guard appropriately.
4. hehehe, for political reasons, follow the damned coding guidelines!!! :)
5. Only the stupid and arrogant think they are perfectly perfect. :)


7 Responses to “On Stack :: Starzan and Cheetae Question”


  1. 1 govz
    August 3, 2008 at 11:30 am

    okay one more thing …
    for those of you who like malloc so much ..
    on heap based allocations ….
    the same goes for it …

    forgive the sample code below …

    —————————————————-
    /* C++ Copy File to NewFileName Function function */
    int8 *temp_buffer(NULL);
    struct stat temp_stat;

    /* get file size */
    stat(file_path,&stat);
    /* very dangerous is the code below, for now please disregard the cast */
    temp_buffer = (int8 *) calloc(1,(size_t) stat.st_size);
    —————————————————-

    of course be my guest, in making a checking for the result of calloc. Yup, it wont hang but will it get the job done??? No way especially if the size of the file is 50Mb.

    To get this done, use a small bucket of memory, copy the file partially using the bucket of memory and a simple while loop, until EOF (end of file) is reached. Now, as for the size of the small bucket of memory (i prefer stack here), this is more of a political thing. hahahah .. ask your leader about it or, try to suggest to him the size of the small bucket. :) and yeah be prepared for the reason why you suggested that size.

    See you, this blog is very very long. I hope you liked this blog because, it is very hard to think of good stuff to write sometimes. And more difficult considering my schedule these days. Take care and please do well in your jobs. YOUR JOBS PUT FOOD ON THE TABLE or whatever extravagance you have in mind. :)

    …SPECIAL THANKS TO ROMMEL….

  2. 2 Harold
    August 4, 2008 at 1:45 am

    Thanx for the info. I will always remember this
    “Remember :
    1. When you can, if it is ok, use STACK.
    2. The STACK is NEVER INFINITE.
    3. Apply a guard appropriately.
    4. hehehe, for political reasons, follow the damned coding guidelines!!!
    5. Only the stupid and arrogant think they are perfectly perfect.

  3. August 5, 2008 at 2:30 am

    i see, after giving thought on this over dinner with Big Papa, at last buo na ung puzzle!

    thanks for sharing the other half and the extension of the puzzle too!

  4. August 5, 2008 at 2:36 am

    just a question…

    “ask your leader about it or, try to suggest to him the size of the small bucket. and yeah be prepared for the reason why you suggested that size”

    what will be the best basis for the size of the small bucket?

  5. 5 Yokam
    August 5, 2008 at 10:21 am

    Hi Govs, it’s me again. Just a silly question. What is the difference between stack overflow and a segmentation fault? Can we catch the stack overflow during compile time or run time? :-)

  6. 6 govz
    August 5, 2008 at 4:55 pm

    @143tatsumi

    1. Why is the answer political?
    - because i am taking this from a standpoint of an outsourced hand. And the issue on stack is really a big item when it comes to embedded. Abuse of stack may mean a fatal error in the machine, causing abberant or “restart” behavior. So therefore, it is better to be safe than sorry, as the old adage goes. ASK THE LEAD, Suggest wisely if he says ok, then go with it or else let him think about it :)

    2. If i were however, the leader … and i was asked the best size of the file-copy bucket?

    2.a INTUITION : For Windows (except WindowsCE) I think 32-64KB will do. Just my guess, no real scientific backing since it has been a long time since i developed on windows. Besides, PCs have very powerful processors as compared to embedded platforms. 1000 instructions is like 1ms or less, i think. Just my engineering intuition.

    And for embedded i would use heap and peg it around 4KB for non-linux and non-unix based OS. For unix and family, i think i can afford to use stack at 32KB->64KB too, provided the OS’ stack allocation per process is set at 2MB or 1MB at least. (I am in the opinion that if someone copies a 30Mb file in an embedded device, NON-STORAGE device, then he or she should wait for it.)

    NOTE however in all platforms, multi-threading may cause problems if we use stack. So if going for multi-threading, use heap.

    2.b TECHNICAL : Very difficult, this one is. (Yoda-style) As far as my experience is concerned, there is no rule of thumb either. However, if u want a real good answer, try testing your application using a time stamp. And then test if u have free time for your own knowledge. Something like : (Sample Only)

    TimeOrig = Timestamp1;
    /* Copy data at 32KB */
    TimeFinal = Timestamp2;
    ———————————————–
    TimeOrig = Timestamp1;
    /* Copy data at 64KB */
    TimeFinal = Timestamp2;
    ———————————————–
    TimeOrig = Timestamp1;
    /* Copy data at 128KB*/
    TimeFinal = Timestamp2;

    There will come a point where the time to transmit is not really worthy the increase in size of the bucket. (I hope I am making sense here.) So find the size which has an enormous cut on time of transmission. :) also try to use multiples of 1024. :)

    Again, like you, i too am a student. I study while i answer some of your questions. Feel free to share knowledge should u find an authoritative answer :)

    To be honest, just go ask the lead hahahahah. But if you are the lead, it is imperative that you study your architecture and predict possible problems. And you should decide too, whether you should use stack or heap. And dont rush learning things, let time ripen you :)

    @Yokam : I dont know if this is a trick question, but i need to get some sleep good friend and sempai. Tomorrow I will try my hand at it :)

  7. 7 govz
    August 17, 2008 at 1:03 pm

    @Yokam : taihen omattaseshimashita .. (sorry i made u wait for a very long time) … i got busy these past few days. Oh well! Here is what i dug up. My stock knowledge overflowed causing faults in the left and right segments of my brain hahaha just kidding mack.

    Also, these are just my learnings online so I might be wrong. By discipline, I am an ECE, so it is not really my forte. I just study what i can, to try and make the gap between my profession and my discipline smaller.

    1. What is the difference between stack overflow and a segmentation fault?
    These two are unique errors mack. But can be interrelated. Assuming we are using a real world system that has 2Kbyte for stack. We then run an infinitely re-entrant program. In this case, when at the final iteration, the 2Kbyte limit is breached, depending on the Memory Management Unit (MMU) design, two possible errors may rise up :

    —————————————————-
    a. stack overflow – because it has exceeded the 2KByte
    b. segmentation fault – because when the re-entrant function tried to ask for more resources, it wrote at an address which it did not have authority over.
    —————————————————-

    Like what wiki said, segmentation is a form of memory protection or organization. Imagine if you have 2Gig of RAM, or whatever, there must be a way to use it for faster operations. Segmentation is one method to manage the memory areas. (Paging is also another.) This method divides the entire memory space into its corresponding segments. For example the data segment (holds all the local and global variables and stuff) and the text segment (holds all the commands and codes).

    Segmentation fault (SEGFAULT or SIGSEV) occurs when for example, a particular segmentation design is like :

    Address Range Segment
    0×0001 -> 0×2000 Kernel Code (Text Segment)
    0x200F -> 0x300F Eat Bulaga Lyrics (Data Segment)

    so if a process tries to :
    a. dereference: *(0×0001) -> SEGFAULT because address 0×0001 is not the proper segment for data.
    b. *(NULL) -> SEGFAULT -> because nobody really knows where null is hahahahah.

    Though you did not ask, i would like to add that PAGE Faults may also be a third probable error when we breach our OS stack limit. :D

    2. Can we catch the stack overflow during compile time or run time?
    I have not seen any compiler that can catch stack overflows. I tried searching but have not seen one that can really detect at compile time. So my answer would be, it can only be detected perfectly at run-time, with good testing techniques. Imagine the example above, compile-wise, a re-entrant function will stay perfectly compilable but may cause segmentation faults or overflows during run-time after a given number of iterations.

    Anyways mack, if u can enlighten us a little more that would be SPLENDID! :D c u around good friend.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.