简体   繁体   中英

Just curiosity, why does this not cause a seg fault?

So it is my understanding that a C string of, for instance "0123456789", would actually occupy an array of 11 chars, 10 chars for the body and one for the terminating null. If that is true then why does the code below NOT cause some sort of error?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char ** argv){

    char * my_string = "0123456789";
    /* my string should occupy 11 bytes */

    int my_len = strlen(my_string);
    /* however, strlen should only return 10, 
        because it does not count the null byte */

    char * new_string = malloc(my_len);
    /* allocate memory 10 bytes wide */

    memcpy(new_string, my_string, my_len);
    /* copy the first 10 bytes from my_string to new_string
        new_string should NOT be null terminated if my understanding
        is correct? */

    printf("%s\n", new_string);

    /* Since new_stirng is NOT null terminated it seems like this should
        cause some sort of memory exception.
        WHY DOES THIS NOT CAUSE AN ERROR?

    */

    return 0;
}

Since new_string is not null terminated I would expect printf to just read forever until it reaches some other applications memory, or a randomly placed 0x00 somewhere and either crash or print something strange. What's going on?

You have created undefined behavior . The behavior is compiler and platform dependent. It could crash. It could work. It could make you toast. It could collapse your computer into a singularity and absorb the solar system.

In your case, it's likely that the memory at new_string[11] was already 0 , which is '\\0' , or the terminating-null character.

Because it's undefined behavior. Undefined behavior does not mean a seg fault, although that's one possibility.

In your case, the particular memory block you got from malloc was never used before (by your program), and it was probably zero-initialized by the OS when it was allocated. Therefore, the 11th byte was likely a zero, and so no error. In a longer-running program, malloc can return a dirty chunk of memory where the 11th byte is not 0, and so you will run into problems at the printf statement. In practice, you'll either print garbage (until the first null is encountered) or segfault if there is no null before the end of the allocated region.

(As others have said, the behavior is formally undefined, I'm just explaining what you saw).

or a randomly placed 0x00 somewhere ... print something strange.

This is commonly observed behavior. What will actually happen is undefined.

This is undefined behaviour. In some cases it could cause a crash it would depend on the memory layout I would imagine

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