c - 移动指针后如何释放一些字节?

标签 c memory pointers

我执行以下操作:

void * myFunction(void) {
    void *someBytes = malloc(1000);
    // fill someBytes

    //check the first three bytes (header)
    if(memcmp(someBytes, "OK+", 3) == 0) {
        // move the pointer (jump over the first three bytes)
        someBytes+=3
    }

    return someBytes;
}

接收方如何释放已分配的指针? 当然,我可以在指针上输入 -3。

但是对于这种情况有最佳实践吗? 是否有一个简单的解决方案仍然允许接收器函数调用 free(someBytes); 因为 someBytes 也可以容纳多个兆字节,所以我想避免 memcpy(malloc(1000) 仅用于示例)。

最佳答案

没有任何办法(除非你碰巧知道确切的偏移量)。最佳实践是存储原始指针的副本,以便稍后可以使用它来释放内存。

void* myFunction(void) {
    void* someBytes = malloc(1000);
    void* pos = someBytes;
    // fill someBytes

    //check the first three bytes (header)
    if(memcmp(pos, "OK+", 3) == 0) {
        // move the pointer (jump over the first three bytes)
        pos+=3
    }

    return someBytes;
}

关于c - 移动指针后如何释放一些字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11592947/

相关文章:

c++ - 为什么我们使用指针而不是简单地创建特定大小的数组?

c++ - 指针可以用来遍历字符数组吗?

c - 内存错误和指向字符串的指针

c++ - 如何计算下面的struct占用的内存空间?

c - 函数参数中的整数双指针

c# - 为什么非托管内存可能占控制台应用程序使用的内存的 60% 以上?

performance - golang slice 分配性能

c - 有没有一种巧妙的方法来执行 strdup() 后跟 strcat()?

c - 如果 (memcmp (版本, "\x0\x0\x0", 3) == 0 )

c - c中文本模式和二进制模式的区别