char * s;
s[400] = 'd';
If it’s not undefined behavior, then does it means I can’t arbitrarily access any part of my RAM outside the stack ? So each time an OS start a processus, it allocates a region of RAM where I can do nasty stuff (except mallocs), since the OS will clean the stack after the process finishes.
Why isn’t the OS able to clean the heap after the process ends ? Does it mean the heap is shared with all other processes ?
If I put too much data in the stack, it is a buffer overflow, but how much can I put in a stack ? Is it OS bound, RAM-size bound, or CPU-cache bound ?
Yes, its behavior is undefined.
sis not initialized, sos[400]is, at best, some indeterminate location in memory.EDIT:
The last three paragraphs of your question have little or nothing to do with the two lines of code that we’ve been discussing. The undefinedness of
s[400] = 'd';has little or nothing to do with stacks, heaps, processes, or anything else.sis uninitialized, so it contains garbage; it may point anywhere in memory, or nowhere.s[400]is, at best, a char object located 400 bytes beyond the undefined location specified by the garbage address stored iss.If you understand that, you probably still have questions. I suggest posting a new question without the code sample.
To partially answer some of what you’ve asked:
Your program may not legitimately attempt to access any memory that’s not part of an object it has created (either by with an object definition like
char foo[1000];or by an allocation likechar *ptr = malloc(1000);). In a particular implementation, there might be some region of memory outside any declared objects that you could get away with playing with, but there is no safe or portable way to do so — and no good reason. If you need to access some memory, allocate it first.The C language itself doesn’t even refer to the “stack” or the “heap”; those are implementation details.
No, the heap is not typically shared between processes. Generally, all stack-allocated and heap-allocated memory is neatly reclaimed by the operating system when your program finishes. (The C standard doesn’t say this, since it only barely concerns itself with what happens outside the execution of your program, but it’s almost universally true, except perhaps in some embedded systems.)