[英]Why does strlen not work on mallocated memory?
我写了以下代码:
[all the required initialization]
printf("longueur de mid: %d\n",mid);
L = (char*) malloc((mid)*sizeof(char));
printf("longueur de L: %d\n",strlen(L));
[data treatment and free()]
使用printf
我得到了这个结果:
longueur de mid: 2
longueur de L: 3
为什么输出不同?
strlen
迭代直到找到一个空字节。 malloc
使分配的空间未初始化,因此可能会随机出现空字节。 毕竟,由于访问了未初始化的内存,这是未定义的行为。
单独确定malloc
块的大小是不可能的。 将大小存储在单独的变量中,如Lsize
和Rsize
。
笔记:
malloc
的结果sizeof(char)
是多余的,因为sizeof(char) == 1
malloc
后free
使用size_t
的相应格式说明符,也就是“ strlen
和sizeof
运算符的返回类型”是%zu
; %d
用于int
s 11正如@chux 在对此答案的评论中指出的那样
正如有人部分提到的那样, strlen() 将输入的输入转换为正确的内存位置,然后该位置增加 1,直到找到空字符。 尝试对来自 malloc() 调用的指针使用 strlen() 的问题在于,返回指针处返回的数据可以是任何内容,具体取决于操作系统处理内存的方式。
如果您希望您的指针在分配内存时引用一组有保证的空字符,您可以使用以下代码:
L = calloc(1,mid+1);
R = calloc(1,n - mid+1);
那么至少当你使用 strlen() 时,你会得到一个零。
如果必须使用 malloc(),则可以使用以下代码:
L = malloc(1,mid+1);
R = malloc(1,n - mid+1);
memset(L,0,mid);
memset(R,0,n - mid);
在这两段代码中,我假设 L 和 R 被声明为char*
。
并且绝对在使用 calloc 和 malloc 分配的所有内存上使用free()
,否则您可能会遇到内存泄漏,这可能会导致您重新启动计算机。
如果您想快速将固定数量的字节放入内存中,请在分配内存后使用:
memset(L,x,mid);
memset(R,x,n - mid);
但是将 x 更改为除零以外的任何值,否则它将为空。
这是一个更符合您期望的示例程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int size=10;
char* a=calloc(1,100); // allocate 100 null's and store pointer to them at 'a'
printf("%d \n",size); // print wanted size
printf("%d \n",strlen(a)); // print length of memory space which = 0
memset(a,'A',size); // put 10 A's at the beginning of allocated memory
printf("%d \n",strlen(a)); // print length again which now = 10
printf("%s \n",a); // print memory (which is 10 A's)
free(a); // free the memory
return 0;
}
即使启用了编译器选项-Wall
和-Wextra
,上面的代码在我的编译器中编译得很好,没有任何警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.