C中的malloc()无法按预期工作 [英] malloc() in C not working as expected

查看:84
本文介绍了C中的malloc()无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C的新手.对不起,如果已经回答了,我找不到直接的答案,所以我们开始吧..

I'm new to C. Sorry if this has already been answered, I could'n find a straight answer, so here we go..

我试图了解malloc()在C中的工作方式.我有以下代码:

I'm trying to understand how malloc() works in C. I have this code:

#define MAXLINE 100

void readInput(char **s)
{
    char temp[MAXLINE];

    printf("Please enter a string: ");
    scanf("%s", temp);

    *s = (char *)malloc((strlen(temp)+1)*sizeof(char)); // works as expected
    //*s = (char *)malloc(2*sizeof(char)); // also works even when entering 10 chars, why?

    strcpy ((char *)*s, temp);
}

int main()
{
    char *str;

    readInput(&str);
    printf("Your string is %s\n", str);
    free(str);

    return 0;
}

问题是为什么当我这样调用malloc()时,为什么程序不会崩溃(或至少除去其余字符)?

The question is why doesn't the program crash (or at least strip the remaining characters) when I call malloc() like this:

*s = (char *)malloc(2*sizeof(char)); // also works even when entering 10 chars, why?

如果我输入两个以上字符的字符串,这是否会导致缓冲区溢出?据我了解,malloc()会为数据分配一个固定的空间,因此确定地仅为两个字符分配空间将允许该字符串最大为一个可用字符("0 \"为第二个),但它仍在打印输入的所有10个字符.

Won't this cause a buffer overflow if I enter a string with more than two characters? As I understood malloc(), it allocates a fixed space for data, so surely allocating the space for only two chars would allow the string to be maximum of one usable character ('0\' being the second), but it still is printing out all the 10 chars entered.

P.S.如果这有什么区别,我正在使用Xcode.

P.S. I'm using Xcode if that makes any difference.

谢谢, 西蒙

推荐答案

效果很好,因为您很幸运!通常,操作系统会给程序一个比2个字节大一点的块.

It works out fine because you're lucky! Usually, a block a little larger than just 2 bytes is given to your program by your operating system.

如果操作系统实际上要求您提供2个字节时给了您16个字节,则您可以写16个字节而无需操作系统注意它.但是,如果您的程序中有另一个malloc()使用了其他14个字节,则会覆盖该变量的内容.

If the OS actually gave you 16 bytes when you asked for 2 bytes, you could write 16 bytes without the OS taking notice of it. However if you had another malloc() in your program which used the other 14 bytes, you would write over that variables content.

OS不在乎您在自己的程序中搞乱什么.仅当您在操作系统给您的内容之外编写内容时,程序才会崩溃.

The OS doesn't care about you messing about inside your own program. Your program will only crash if you write outside what the OS has given you.

尝试写200个字节,看看它是否崩溃.

Try to write 200 bytes and see if it crashes.

malloc()free()使用一些堆空间来维护有关已分配内存的信息.该信息通常存储在存储块之间.如果缓冲区溢出,则此信息可能会被覆盖.

malloc() and free() uses some of the heap space to maintain information about allocated memory. This information is usually stored in between the memory blocks. If you overflow a buffer, this information may get overwritten.

这篇关于C中的malloc()无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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