为什么strlen在分配不当的内存上不起作用? [英] Why does strlen not work on mallocated memory?

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

问题描述

我编写了以下代码:

[all the required initialization]

printf("longueur de mid: %d\n",mid);
printf("longueur de n-mid: %d\n",n - mid);

L = (char*) malloc((mid)*sizeof(char)); 
R = (char*) malloc((n - mid)*sizeof(char)); 

printf("longueur de L: %d\n",strlen(L));
printf("longueur de R: %d\n",strlen(R));

[data treatment and free()]

使用printf,我得到了以下结果:

And with the printf I got this result:

longueur de mid: 2
longueur de n-mid: 2
longueur de L: 3
longueur de R: 3

输出为何不同?

推荐答案

strlen 迭代直到找到空字节. malloc使分配的空间保持未初始化状态,因此可能会随机出现一个空字节.毕竟,由于未初始化的内存的访问,它是未定义的行为.

strlen iterates until a null byte is found. malloc leaves the allocated space uninitialized, so a null byte may occur randomly. After all, it's undefined behavior due to the access of uninitialized memory.

无法单独确定malloc块的大小.将大小存储在单独的变量中,例如LsizeRsize.

Determining the size of a mallocated block alone is not possible. Store the size in seperate variables like Lsize and Rsize.

注意:

  • 不要转换malloc <的结果/li>
  • 乘以sizeof(char)sizeof(char) == 1一样是多余的
  • malloc
  • 之后使用free
  • size_t的相应格式说明符,又称为"strlen的返回类型和sizeof运算符"为%zu%d用于int s 1
  • don't cast the result of malloc
  • multiplying by sizeof(char) is redundant as sizeof(char) == 1
  • use free after malloc
  • the corresponding format specifier for size_t, a.k.a. "return type of strlen and the sizeof operator" is %zu; %d is used on ints1

1 如@chux在此答案的注释中指出的

1 as @chux noted in the comments to this answer

这篇关于为什么strlen在分配不当的内存上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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