为什么strlen在分配不当的内存上不起作用? [英] Why does strlen not work on mallocated memory?
本文介绍了为什么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
块的大小.将大小存储在单独的变量中,例如Lsize
和Rsize
.
Determining the size of a malloc
ated block alone is not possible. Store the size in seperate variables like Lsize
and Rsize
.
注意:
- 不要转换
malloc
<的结果/li> - 乘以
sizeof(char)
与sizeof(char) == 1
一样是多余的 - 在
malloc
之后使用 -
size_t
的相应格式说明符,又称为"strlen
的返回类型和sizeof
运算符"为%zu
;%d
用于int
s 1
free
- don't cast the result of
malloc
- multiplying by
sizeof(char)
is redundant assizeof(char) == 1
- use
free
aftermalloc
- the corresponding format specifier for
size_t
, a.k.a. "return type ofstrlen
and thesizeof
operator" is%zu
;%d
is used onint
s1
1 如@chux在此答案的注释中指出的
1 as @chux noted in the comments to this answer
这篇关于为什么strlen在分配不当的内存上不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文