如何在 C 中使用 calloc() ?

发布于 2024-10-19 11:57:06 字数 468 浏览 6 评论 0原文

如果我的字符串在这个程序中超过 9 个字符,我不应该收到错误吗?

// CString.c
// 2.22.11

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

main()
{
    char *aString = calloc(10, sizeof(char));

    if (aString == NULL)
    {
        return 1;
    }

    printf("PLEASE ENTER A WORD: ");
    scanf("%s", aString);

    printf("YOU TYPED IN: %s\n", aString);
    //printf("STRING LENGTH: %i\n", strlen(aString));
}

谢谢布拉格曼

Shouldn't I get an error if my string goes over 9 characters long in this program?

// CString.c
// 2.22.11

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

main()
{
    char *aString = calloc(10, sizeof(char));

    if (aString == NULL)
    {
        return 1;
    }

    printf("PLEASE ENTER A WORD: ");
    scanf("%s", aString);

    printf("YOU TYPED IN: %s\n", aString);
    //printf("STRING LENGTH: %i\n", strlen(aString));
}

Thanks

blargman

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我不在是我 2024-10-26 11:57:06

您不会收到编译器错误,因为语法是正确的。不正确的是逻辑,并且您得到的是未定义的行为,因为您正在写入超出缓冲区末尾的内存。

为什么这是未定义的行为?好吧,您没有分配该内存,这意味着它不属于您 - 您正在侵入一个用警戒带封闭的区域。考虑您的程序是否直接使用缓冲区之后的内存。您现在已经覆盖了该内存,因为您超出了缓冲区。

考虑使用这样的大小说明符:

scanf("%9s", aString);

这样就不会溢出缓冲区。

You don't get a compiler error because the syntax is correct. What is incorrect is the logic and, what you get is undefined behavior because you are writing into memory past the end of the buffer.

Why is it undefined behavior? Well, you didn't allocate that memory which means it doesn't belong to you -- you are intruding into an area that is closed off with caution tape. Consider if your program is using the memory directly after the buffer. You have now overwritten that memory because you overran your buffer.

Consider using a size specifier like this:

scanf("%9s", aString);

so you dont overrun your buffer.

陌若浮生 2024-10-26 11:57:06

是的,你有一个错误。最不幸的是你不知道这一点。当某些事情神秘地崩溃时(如果你幸运的话),或者当你的客户的律师来起诉你时(如果你不幸运的话),你可能会在程序稍后的过程中知道这一点。

Yes, you got an error. And the most unfortunate part is that you don't know about it. You might know about it later on in the program when something mysteriously crashes (if you're lucky), or when your client's lawyers come to sue you (if you're not).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文