gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:50 27 4
gpt4 key购买 nike

我做了以下事情:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com