我写了以下代码:
[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()]
Run Code Online (Sandbox Code Playgroud)
随着printf我得到了这个结果:
longueur de mid: 2
longueur de n-mid: 2
longueur de L: 3
longueur de R: 3
Run Code Online (Sandbox Code Playgroud)
为什么输出会有所不同?
cad*_*luk 11
strlen迭代直到找到空字节.malloc将分配的空间保留为未初始化,因此可以随机出现空字节.毕竟,由于未初始化内存的访问,它是未定义的行为.
malloc不可能单独确定块的大小.将大小存储在单独的变量中,例如Lsize和Rsize.
笔记:
mallocsizeof(char)是多余的sizeof(char) == 1free之后使用mallocsize_t,又名"返回类型strlen和sizeof运算符" %zu; %d用于ints 11作为@chux在对此答案的评论中注明
| 归档时间: |
|
| 查看次数: |
1206 次 |
| 最近记录: |