Getting no segmentation fault when exceeding the s

2019-08-05 09:41发布

This question already has an answer here:

I use malloc to allocate n (string length of y) bytes for x. However after copying y to x , I added 3 more characters including '\0' in x and i got no error.

Shouldn't I get an error for trying to assign values to unallocated memory since I've allocated space enough for only 10 characters? Is this undefined behavior?

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

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

    char *x,*y="123465412";
    int i,n;

    n=strlen(y);


    x=(char *)malloc(sizeof(char)*n);

    for(i=0; i<n ; i++)
        x[i]=y[i];

    x[i]='5';
    x[i+1]='5';
    x[i+2]='\0';

    puts(x);



}

1条回答
时光不老,我们不散
2楼-- · 2019-08-05 10:22

No. In C there are no (builtin) tests for overriding a malloc()'ed buffer. After one malloced block You'll find another malloced block in memory. So if you write beyond a malloced buffer you simply modify some other block. (Which is very dangerous of course and will produce weird behaviour of your code: usually termed unexpected results.)

查看更多
登录 后发表回答