写的字符多于分配的字符.为什么不失败? [英] Writing more characters than malloced. Why does it not fail?

查看:106
本文介绍了写的字符多于分配的字符.为什么不失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的工作不会引发某种细分错误?

Why does the following work and not throw some kind of segmentation fault?

char *path = "/usr/bin/";
char *random = "012";

// path + random + \0
// so its malloc(13), but I get 16 bytes due to memory alignment (im on 32bit)
newPath = (char *) malloc(strlen(path) + strlen(random) + 1);

strcat(newPath, path);
strcat(newPath, "random");
// newPath is now: "/usr/bin/012\0" which makes 13 characters.

但是,如果我添加

strcat(newPath, "RANDOMBUNNIES");

该调用是否应该失败,因为strcat使用的内存多于分配的内存?因此,不应该

shouldn't this call fail, because strcat uses more memory than allocated? Consequently, shouldn't

free(newPath)

也会失败,因为它尝试释放16个字节,但我使用了26个字节("/usr/bin/012RANDOMBUNNIES \ 0")?

also fail because it tries to free 16 bytes but I used 26 bytes ("/usr/bin/012RANDOMBUNNIES\0")?

非常感谢!

推荐答案

大多数情况下,这种溢出问题不会使您的程序在浓烟和硫磺味中爆炸.更为微妙的是:在超出运行变量之后分配的变量将被更改,从而在以后导致程序无法解释且看似随机的行为.

Most often this kind of overrun problems doesn't make your program explode in a cloud of smoke and the smell of burnt sulphur. It's more subtle: the variable that is allocated after the overrun variable will be altered, causing unexplainable and seemingly random behavior of the program later on.

这篇关于写的字符多于分配的字符.为什么不失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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