为什么分配的内存与字符串的大小不同? [英] Why does allocated memory is different than the size of the string?

查看:54
本文介绍了为什么分配的内存与字符串的大小不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

char    **ptr;

str = malloc(sizeof(char *) * 3); // Allocates enough memory for 3 char pointers
str[0] = malloc(sizeof(char) * 24);
str[1] = malloc(sizeof(char) * 25);
str[2] = malloc(sizeof(char) * 25);

当我使用一些 printf 打印每个指针的内存地址时:

When I use some printf to print the memory adresses of each pointer:

printf("str[0] = '%p'\nstr[1] = '%p'\nstr[2] = '%p'\n", str[0], str[1], str[2]);

我得到这个输出:

str[0] = '0x1254030'
str[1] = '0x1254050'
str[2] = '0x1254080'

我期望第二个地址对应的数字是第一个地址对应的数字和24的总和,24对应字符串str[0]的字节大小(因为一个字符的大小为 1 个字节).我预计第二个地址对应的数字是 0x1254047,考虑到这个数字是以 16 为底的 (0123456789abcdef).

I expected the number corresponding to the second adress to be the sum of the number corresponding to the first one, and 24, which corresponds to the size of the string str[0] in bytes (since a char has a size of 1 byte). I expected the number corresponding to the second adress to be 0x1254047, considering that this number is expressed in base 16 (0123456789abcdef).

在我看来,我发现了一个模式:从字符串中的 24 个字符开始,其中每多包含 16 个字符,所使用的内存就大 16 个字节.例如,一个 45 个字符长的字符串使用 64 个字节的内存,一个 77 个字符长的字符串使用 80 个字节的内存,一个 150 个字符长的字符串使用 160 个字节的内存.

It seems to me that I spotted a pattern: from 24 characters in a string, for every 16 more characters contained in it, the memory used is 16 bytes larger. For example, a 45 characters long string uses 64 bytes of memory, a 77 characters long string uses 80 bytes of memory, and a 150 characters long string uses 160 bytes of memory.

这是模式的说明:

我想了解为什么分配的内存不等于字符串的大小.为什么它遵循这种模式?

I would like to understand why the memory allocated isn't equal to the size of the string. Why does it follow this pattern?

推荐答案

三个原因:

(1) 字符串 "ABC" 包含 4 个字符,因为 C 中的每个字符串都必须有一个终止符 '\0'.

(1) The string "ABC" contains 4 characters, because every string in C has to have a terminating '\0'.

(2) 许多处理器都有内存地址对齐问题,当 malloc() 分配的任何块从 4 或 8 的倍数或任何自然"内存大小的地址开始时,这使得它最有效.

(2) Many processors have memory address alignment issues that make it most efficient when any block allocated by malloc() starts on an address that is a multiple of 4, or 8, or whatever the "natural" memory size is.

(3) malloc() 函数本身需要一些内存来存储有关已分配内容的信息,以便 free() 知道要做什么.

(3) The malloc() function itself requires some memory to store information about what has been allocated where, so that free() knows what to do.

这篇关于为什么分配的内存与字符串的大小不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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