我正在审查我的一些旧代码以及我用于为 c 字符串初始化 malloc() 的方法似乎可行,但仔细检查后我担心可能存在缓冲区溢出。
我目前的风格是获取 char 的 size_t 并将其乘以我想要的值。例如:
#include <stdlib.h>
#include <limits.h>
int main(int argc,char **argv)
{
char *string = malloc(sizeof(char) * PATH_MAX + 1);
/* do stuff */
free(string);
return somevalue;
}
但是我的旧代码只是将 size_t 的值转换为我想要的值,例如而不是使用
char *string = malloc(sizeof(char) * PATH_MAX + 1);
我用过
char *string = malloc((size_t)PATH_MAX + 1);
由于我正在分配一个字符数组,malloc 将采用数据类型的值并将其用作正确的字节大小,从而使前面的两个语句类似,或者我是否在给定的假设下造成了缓冲区溢出的意外机会要放入“string”的字符串小于 PATH_MAX 的大小。
最佳答案
sizeof(char)
很少提供信息。根据定义,它始终为 1 且类型为 size_t
。
// Both attempt to allocate the same amount.
char *string1 = malloc(sizeof(char) * PATH_MAX + 1);
char *string2 = malloc((size_t)PATH_MAX + 1);
以下内容略有不同。虽然更简单,但根据 PATH_MAX
的类型,迂腐地说,PATH_MAX + 1
可能会溢出。
char *string3 = malloc(PATH_MAX + 1);
更好的是
char *string4 = malloc(PATH_MAX + 1u);
迂腐地这应该是
char *string5 = malloc(PATH_MAX + (size_t)1); // or like string2 above
或者,使用 sizeof_referenced_variable * element_count
习惯用法并避免类型问题。
string6 = malloc(sizeof *string6 * (PATH_MAX + 1u));
当 N
是公式时,使用 sizeof_this * N
与 N * sizeof_this
相比有优势。
int rows, columns;
...
v------v----- size_t multiplication
matrix1 = malloc(sizeof *matrix1 * rows * columns);
v----------- int multiplication (overflow possible)
| v- size_t multiplication
matrix2 = malloc(rows * columns * sizeof *matrix2);
当然如果产品溢出size_t
数学,代码是SOL .
关于在 malloc 期间转换 size_t 以在 c 中初始化 char* 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39544837/