用malloc初始化后,如何获得char *指向的连续内存的长度?

时间:2020-06-08 12:08:31

标签: c string memory char malloc

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char* buffer = malloc(1000*sizeof(char));
    memset(buffer,'\0',1000);

    printf("%ld\n",sizeof buffer);    // Size of Pointer
    printf("%ld\n",sizeof *buffer);   // Size of Memory Block pointed at by buffer
    printf("%ld\n",strlen(buffer));   // Length of String
    return 0;
}


//  Output:-
//  8
//  1
//  0

代码工作正常。

输出符合预期,但是如果我不知道长度,我如何找到用malloc初始化的连续内存的长度?

1 个答案:

答案 0 :(得分:4)

没有标准的方法可以找出多块分配的内存。

由您自己来跟踪尺寸。