Getting no segmentation fault when exceeding the size that was allocated for a char * [duplicate]

被刻印的时光 ゝ 提交于 2020-01-05 04:36:15

问题


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



来源:https://stackoverflow.com/questions/29181344/getting-no-segmentation-fault-when-exceeding-the-size-that-was-allocated-for-a-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!