【发布时间】:2021-07-24 14:59:14
【问题描述】:
我正在对 malloc 函数的使用做一些测试。 这是我正在使用的代码
#include <stdio.h>
#include <stdlib.h>
int main(){
char * string = NULL;
int size = 0;
printf("Insert the number of caracters that u want to enter: ");
scanf("%d", &size);
string = malloc(size * sizeof(char)); //(char *)calloc(size, char)
if(string != NULL){
printf("Insert the string of %d size: ", size);
scanf("%s", string); //gets(string)
printf("The string that u entered is \"%s\"\n", string);
}
free(string);
return 0;
}
现在,如果我输入 size = 4,然后输入类似“12345678910”的字符串,则 printf 的输出是正确的,即使我输入大小为 0 并且输入长字符串,printf 的输出也是正确的。 为什么会这样?
【问题讨论】:
-
请记住分配
1比“真实”字符数更多以占'\0',即。为字符串"hello"分配6字节。 -
除了我的其他评论之外,您正在通过尝试访问不属于您的程序的内存来调用 Undefined Behaviour。
-
它“有效”,因为未定义的行为意味着未定义的行为。它可能会起作用,也可能会崩溃。
-
我知道我正在调用未定义行为,这是我测试的目的,但我认为我的代码会崩溃或打印一些无法理解的字符。在我测试代码的所有时间里,字符串都是正确打印的。我从一门课程中获取代码,我想测试它以寻找问题