How does free know how much to free?

后端 未结 11 2133
情话喂你
情话喂你 2020-11-22 03:28

In C programming, you can pass any kind of pointer you like as an argument to free, how does it know the size of the allocated memory to free? Whenever I pass a pointer to s

11条回答
  •  长情又很酷
    2020-11-22 04:07

    To answer the second half of your question: yes, you can, and a fairly common pattern in C is the following:

    typedef struct {
        size_t numElements
        int elements[1]; /* but enough space malloced for numElements at runtime */
    } IntArray_t;
    
    #define SIZE 10
    IntArray_t* myArray = malloc(sizeof(intArray_t) + SIZE * sizeof(int));
    myArray->numElements = SIZE;
    

提交回复
热议问题