超过为char分配的大小时,没有分段错误* [英] Getting no segmentation fault when exceeding the size that was allocated for a char *

查看:88
本文介绍了超过为char分配的大小时,没有分段错误*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用malloc为x分配n个(y的字符串长度)字节.但是,将y复制到x之后,我在x中又添加了3个字符,包括"\ 0",但没有出现错误.

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.

由于我仅分配了10个字符的空间,尝试为未分配的内存分配值时不会出现错误? 这是未定义的行为吗?

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



}

推荐答案

否.在C中,没有用于覆盖malloc()缓冲区的(内置)测试.在一个已分配的块之后,您将在内存中找到另一个已分配的块.因此,如果您写的超出了分配的缓冲区,则只需修改其他一些块. (当然,这非常危险,并且会产生奇怪的代码行为:通常称为意外结果.)

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

这篇关于超过为char分配的大小时,没有分段错误*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆