C中的内存分配和释放

时间:2022-09-06 19:59:41

I am allocating memory to a void * of some specific size. After allocating I want to show a memory leak and want to deallocate that memory but to some particular size given.

我将内存分配给某个特定大小的void *。分配后,我想显示内存泄漏,并希望释放该内存,但要给出一些特定的大小。

For example : I have allocated memory of 1000bytes using malloc now I want to deallocate 500 bytes of this 1000 bytes.

例如:我已经使用malloc分配了1000字节的内存,现在我想释放这1000字节的500字节。

How can i do that?

我怎样才能做到这一点?

Thank you and Regards

谢谢你们

2 个解决方案

#1


2  

There is no way to free just some memory from allocated one. But have option of realloc is attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

没有办法从分配的内存中释放一些内存。但是,realloc的选项是尝试调整先前通过调用malloc或calloc分配的ptr指向的内存块。

void func()
{
        //allocate 1000 byte
    void *ptr = malloc(1000);

        //reallocate with new size 
    ptr = realloc(ptr ,500);
        //Now you have memory of 500 byte


      //free memory after use
    return;
}

#2


1  

There is no way to deallocate just 500 bytes out of 1000bytes allocated.

没有办法从分配的1000字节中释放500个字节。

free() function takes pointer returned by only malloc() and its family functions for allocation. So it will free all the memory allocated.

free()函数接受仅由malloc()返回的指针及其族函数进行分配。所以它将释放所有分配的内存。

If your purpose is to show memory leak then

如果你的目的是显示内存泄漏那么

void func()
{
  void *p =  malloc(1000);
  // Some stuff
  return;
}

Memory allocated is not freed here and you have a memory leak.

分配的内存未在此处释放,并且您有内存泄漏。

#1


2  

There is no way to free just some memory from allocated one. But have option of realloc is attempts to resize the memory block pointed to by ptr that was previously allocated with a call to malloc or calloc.

没有办法从分配的内存中释放一些内存。但是,realloc的选项是尝试调整先前通过调用malloc或calloc分配的ptr指向的内存块。

void func()
{
        //allocate 1000 byte
    void *ptr = malloc(1000);

        //reallocate with new size 
    ptr = realloc(ptr ,500);
        //Now you have memory of 500 byte


      //free memory after use
    return;
}

#2


1  

There is no way to deallocate just 500 bytes out of 1000bytes allocated.

没有办法从分配的1000字节中释放500个字节。

free() function takes pointer returned by only malloc() and its family functions for allocation. So it will free all the memory allocated.

free()函数接受仅由malloc()返回的指针及其族函数进行分配。所以它将释放所有分配的内存。

If your purpose is to show memory leak then

如果你的目的是显示内存泄漏那么

void func()
{
  void *p =  malloc(1000);
  // Some stuff
  return;
}

Memory allocated is not freed here and you have a memory leak.

分配的内存未在此处释放,并且您有内存泄漏。