【发布时间】:2017-04-18 12:08:44
【问题描述】:
我目前正在学习 C 编程,由于我是一名 python 程序员,我对 C 的内部工作原理并不完全确定。我只是偶然发现了一件非常奇怪的事情。
void test_realloc(){
// So this is the original place allocated for my string
char * curr_token = malloc(2*sizeof(char));
// This is really weird because I only allocated 2x char size in bytes
strcpy(curr_token, "Davi");
curr_token[4] = 'd';
// I guess is somehow overwrote data outside the allocated memory?
// I was hoping this would result in an exception ( I guess not? )
printf("Current token > %s\n", curr_token);
// Looks like it's still printable, wtf???
char *new_token = realloc(curr_token, 6);
curr_token = new_token;
printf("Current token > %s\n", curr_token);
}
int main(){
test_realloc();
return 0;
}
所以问题是:为什么我能够在字符串中写入比分配大小更多的字符?我知道我应该自己处理分配的内存,但这是否意味着当我在指定内存之外写入时没有迹象表明有问题?
我想要完成的事情
- 分配一个 4 字符 (+ null char) 字符串,我将在其中写入我的姓名的 4 个字符
- 重新分配内存以容纳我名字的最后一个字符
【问题讨论】:
-
这是未定义的行为。
-
请详细说明?
-
Undefined Behavior 一切皆有可能发生.....
-
这是informative list of undefined behaviour。它包含一些 UB,而不是全部,并且它包含的一些可能是不正确的(只是提供信息,而不是规范)。例如“指示字符串或宽字符串实用函数访问超出对象末尾的数组(7.24.1、7.29.4)。”
-
2 * 1 = 2 .... sizeof(char)