小编Adi*_*hai的帖子

C 如何释放动态分配数组的所有字节?

#include <stdio.h>
#include <stdlib.h>

int main(){

    int * ptr = (int*)malloc(sizeof(int)*100); // Allocated space for 100 integers

    // Some code

    free(ptr); // Calling free with ptr as argument

    return 0;
}
Run Code Online (Sandbox Code Playgroud)
  1. 如何释放所有 400 字节(在我的例子中)?ptr仅包含内存中一个字节的地址,而且我没有传递任何其他参数来指定动态数组的大小,以便它可以运行循环并释放所有字节

  2. 如果我这样做会发生什么:

    ptr++;
    free(ptr);
    
    Run Code Online (Sandbox Code Playgroud)
  3. 既然我们无法通过给出指针来检索堆中数组的大小,那么这意味着malloc()不知道保留了多少字节,ptr那么为什么它不从前一个数组的中间开始分配另一个堆内存呢?

c malloc free pointers dynamic-memory-allocation

1
推荐指数
1
解决办法
139
查看次数

标签 统计

c ×1

dynamic-memory-allocation ×1

free ×1

malloc ×1

pointers ×1