Why am I not getting a stack break error when I access memory outside of what I have allocated?
This is where I should get a stack split error. Why am I not getting this?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct mun
{
int len;
char str[0];
};
int main(void)
{
//char mp[8];
struct mun *p=malloc(sizeof(struct mun)+2);
p->len=8;
strcpy(p->str,"munjalllfff");
//strcpy(mp,"munjalllfff");
printf("%s\n",p->str);
//printf("%s\n",mp);
return 0;
}
Please explain if possible, or (a name or link for a topic will suffice for me.)
source to share
Most C implementations will not get in the way of protecting the stack or heap from being overwritten with just a few bytes. (There is a library, aptly named Electric Fence , that can do this.) Chances are, if you write enough data, you will end up writing outside the valid address space and the program will crash anyway (this depends on many factors such as OS, compiler, options). As you may have noticed, this answer is very vague. The reason is that what you are doing is called technically undefined by the C standard, which means that an implementation can do anything, including nothing.
Why is that? Why is there no provision in the C standard that says
3.1.4.1.5 When attempting to access outside the allocated memory, an equivalent statement is executed
fprintf(stderr, "illegal access at %p\n", (void *)address);
.
The reason is that it will be a heavy burden on implementation. Perhaps the compiler should generate code to check for illegal accesses after almost all pointer changes and function calls. C is, by design, a tiny language in which programmers get basically what they ask for and also "invisible code".
And then it stderr
can be closed or non-existent :-)
source to share