首页 > 解决方案 > 如何打印内存和缓冲区的长度?

问题描述

我需要打印内存和缓冲区的大小?

他们是另一种方式吗?

size_t len;
len = strlen(input);
printf("******************len is : %d\n", len)

我刚刚编辑了“输入”实际上是“缓冲区”的问题

标签: cmemorystacksizebuffer

解决方案


可以使用自定义的malloc方法,来自redis

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

void* zmalloc(size_t size) {
    void* ptr = malloc(size + sizeof(size_t));
    *((size_t*)ptr) = size;
    return ptr + sizeof(size_t);
}

size_t zmalloc_size(void* ptr) {
    void* real_ptr = ptr - sizeof(size_t);
    return *((size_t*)real_ptr);
}

int main() {
    void* ptr = zmalloc(100);
    printf("%zu", zmalloc_size(ptr));
}

推荐阅读