写比 malloced 更多的字符.为什么它不会失败? [英] Writing more characters than malloced. Why does it not fail?

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

问题描述

为什么以下工作不会引发某种分段错误?

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

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

// path + random + 
// 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" 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")?

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

非常感谢您!

推荐答案

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

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.

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

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