您如何知道要使用malloc()分配多少空间? [英] How do you know how much space to allocate with malloc()?

查看:96
本文介绍了您如何知道要使用malloc()分配多少空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C语言的新手,我来自C#.我一直在学习有关内存管理和malloc()函数的知识.我也遇到了这段代码:

I'm a total C newbie, I come from C#. I've been learning about memory management and the malloc() function. I've also came across this code:

char *a_persons_name = malloc(sizeof(char) + 2);

我不明白的是它为a_persons_name分配了多少空间.它是分配2个字符(例如AB)还是其他?

What I don't understand is how much space this is allocating for a_persons_name. Is it allocating 2 characters (eg. AB) or something else?

我还知道,有时您可以通过malloc获得幸运"并使用未分配的空间(这可能导致数据损坏和段错误).那么我怎么知道我要分配多少空间以及需要多少空间?

I also know that you can sometimes get "lucky" with malloc and use unallocated space (which can result in data corruption and seg faults). So how do I know how much space I'm allocating and how much I will need?

推荐答案

该代码段为2个字符的名称分配了足够的空间.

That snippet is allocating enough space for a 2-character name.

通常,字符串缓冲区将从某个地方(即I/O)填充.如果提前不知道字符串的大小(例如,从文件或键盘读取),则通常使用以下三种方法之一:

Generally the string buffer is going to be filled from somewhere, i.e. I/O. If the size of the string isn't known ahead of time (e.g. reading from file or keyboard), one of three approaches are generally used:

  • 为任何给定的字符串定义最大大小,分配该大小+ 1(对于空终止符),最多读取太多字符,如果提供了太多字符,则错误或盲目截断.不太用户友好.

  • Define a maximum size for any given string, allocate that size + 1 (for the null terminator), read at most that many characters, and error or blindly truncate if too many characters were supplied. Not terribly user friendly.

分阶段重新分配(最好使用几何级数,例如加倍,以避免出现二次行为),并继续阅读直到到达末尾.不太容易编码.

Reallocate in stages (preferably using geometric series, e.g. doubling, to avoid quadratic behaviour), and keep on reading until the end has been reached. Not terribly easy to code.

分配一个固定的大小,希望不会超过该大小,并且在此假设失败时会严重崩溃(或被拥有).易于编码,易于破解.例如,请参阅标准C库中的gets. (从不使用此功能.)

Allocate a fixed size and hope it won't be exceeded, and crash (or be owned) horribly when this assumption fails. Easy to code, easy to break. For example, see gets in the standard C library. (Never use this function.)

这篇关于您如何知道要使用malloc()分配多少空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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