简体   繁体   English

我可以释放最初从另一个指针分配的内存吗?

[英]Can I free memory originally allocated from another pointer?

If I allocated memory from another pointer, then declare a pointer equal to the other pointer, can I then free the memory allocated with the first pointer by using free() on the new pointer? 如果我从另一个指针分配了内存,然后声明了一个与另一个指针相等的指针,那么我可以通过在新指针上使用free()由第一个指针分配的内存吗?

Example: 例:

typedef struct foo{
  int n;
  char c;
} foo;

foo* bar = malloc(sizeof(foo));
foo* tmp = bar; // declaring pointer identical to other pointer

free(tmp); // can I do this to free *bar?

Yes, it is completely fine. 是的,完全可以。

Your implementation of malloc will most likely mark the chunk of memory as allocated before returning a pointer to it. 您的malloc实现很可能会在返回指向内存的块之前将其标记为已分配。

Now you can have as many pointer variables as you want which point to this chunk of memory and you can free that memory by calling free on any of them. 现在,您可以拥有任意数量的指向此内存块的指针变量,并且可以通过对任意一个变量调用free来释放该内存。

The pointer itself doesn't contain information about whether the memory it points to has been allocated. 指针本身不包含有关它所指向的内存是否已分配的信息。 It just points to it. 它只是指向它。

int* i = malloc(sizeof(int) * 23);
int* j = i;

free(j); 
// free(i); // this is undefined behavior, the memory was already freed

Yes you can do what you are asking about. 是的,您可以做您要问的事情。 But it is not another pointer, what you are freeing is the same pointer. 但这不是另一个指针,您释放的是相同的指针。 When malloc returns a pointer, it is essentially giving you an integer that is the address of the start of the chunk of memory that it has reserved for you. malloc返回一个指针时,它实际上是为您提供一个整数,该整数是它为您保留的内存块的开始地址。 When you are done are done with the memory, you pass that address to free . 完成对内存的处理后,将该地址传递给free As far as free is concerned, there is no difference between: free而言,两者之间没有区别:

free(malloc(17));

,

void *p = malloc(17);
free(p);

or 要么

void *p1 = malloc(17);
void *p2 = p1;  
free(p2);

In all of these cases the value returned from malloc is getting to free , and that is all that matters. 在所有这些情况下,从malloc返回的值将变为free ,这就是所有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM