-->

Getting no segmentation fault when exceeding the s

2019-08-05 09:25发布

问题:

This question already has an answer here:

  • Array index out of bound in C 9 answers

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:

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