我执行以下操作:
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/