简体   繁体   中英

Why am I not getting stack smashing error when I access memory beyond what I allocated?

I should get stack smashing error here . What is the reason I am not getting it?

#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 topic name or link will enough for me.)

Most C implementations won't bother to protect the stack or heap from being overwritten by a few bytes only. (There's a library aptly named Electric Fence that can do so). Chances are, if you write enough data, you'll eventually write beyond the allowed address space and the program crashes in one way or another (this depends on many factors, like OS, compiler, options). As you noticed by now, this answer is very vague. The reason is that what you do is technically called undefined behavior by the C Standard, which means the implementation is free to do anything, including nothing.

Why is it so? Why doesn't the C Standard have a clause saying

3.1.4.1.5 When an access outside of allocated memory is attempted, a statement equivalent to fprintf(stderr, "illegal access at %p\\n", (void *)address); shall be executed.

The reason is that this would place a heavy burden on the implementation. The compiler probably would have to generate code to check for illegal accesses after almost all pointer modifications and function calls. C is, by design, a tiny language where programmers get mostly what they ask for and no "invisible code" in addition.

And then, stderr may be closed or non-existent :-)

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

这不在堆栈上,使用free(p),你可能会看到一些错误!

This is clearly Undefined behavior . It may work and may not!

To avoid it you should use strncpy() while copying the string.

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

Also don't forget to free() the memory you have allocated using malloc() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM