gpt4 book ai didi

c - malloc 和 scanf 字符串

转载 作者:太空宇宙 更新时间:2023-11-04 06:03:46 24 4
gpt4 key购买 nike

下面的一个简单程序使用 malloc 和 scanf 以及 %s 来获取下面的字符串,给我一个我无法理解的输出。虽然我只“malloced”了 5 个字节,但我的输入字符串已超过上述大小但没有段错误。scanf 是否覆盖了 malloc 分配?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
char * name;
int SZSTRING;

printf("Enter size of name :");
scanf("%d", &SZSTRING);
name = (char*) malloc ((SZSTRING + 1) * sizeof(char));

printf("Enter name :");
scanf("%s", name);
printf("len of 'name' : %d\n",strlen(name));

printf("name final: \"%s\"\n",name);
free(name);

return 0;
}

Output:

OptiPlex-380:~/gsa/compile$ gcc -o try try.c
OptiPlex-380:~/gsa/compile$ ./try
Enter size of name :4
Enter name :qwertyui
len of 'name' : 8
name final: "qwertyui"

我在这里还注意到一件事:用

    //scanf("%s", name);

输出显示

len of 'name'= 0

和'malloced' 位置实际上被memset 为NULL。但是它的 calloc 而不是 malloc 根据手册页将分配的字节初始化为 0???

最佳答案

它可能看起来“有效”,但这只是因为您很幸运。当我在一个编译器上运行您的代码时,它在另一个编译器上“工作”,但由于堆损坏而崩溃。如果您想使用 scanf(),最好的办法是让 scanf() 为您分配内存:

scanf("%ms", &name); // compiled with -std=c99 this will allocate the correct amount
// of memory for you. You can use "%as" if you're using -std=c89

另请记住 scanf()有一个返回值(它告诉您成功匹配和分配的输入项的数量),检查它以了解它是否有效很重要。

虽然我们在进行良好实践,但您 shouldn't typecast the return value of malloc()

另一种不使用 scanf() 的方法是使用 fgets()相反:

fgets( name, SZSTRING, stdin);

关于c - malloc 和 scanf 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500880/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com