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.)

+3


source to share


4 answers


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 :-)

+12


source


You are calling undefined behavior. Anything could happen. If you're lucky it will crash, if you're lucky it will sign you up for Google +.



+11


source


It's not on the stack, use free (p) and you might see some errors!

+1


source


This is clearly Undefined behavior . It can work and it can't!

To avoid this, you should use strncpy()

when copying a string.

strncpy(p->str,"munjalllfff",sizeof(p->str));

Also don't forget the free()

memory you allocated using malloc()

.

0


source







All Articles