If free() knows the length of my array, why can't I ask for it in my own code?

前端 未结 9 693
天命终不由人
天命终不由人 2020-12-02 18:20

I know that it\'s a common convention to pass the length of dynamically allocated arrays to functions that manipulate them:

void initializeAndFree(int* anArr         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 18:50

    After reading Klatchko's answer, I myself tried it and ptr[-1] indeed stores the actual memory (usually more than the memory we asked for probably to save against segmentation fault).

    {
      char *a = malloc(1);
      printf("%u\n", ((size_t *)a)[-1]);   //prints 17
      free(a);
      exit(0);
    }
    

    Trying with different sizes, GCC allocates the memory as follows:

    Initially memory allocated is 17 bytes.
    The allocated memory is atleast 5 bytes more than requested size, if more is requested, it allocates 8 bytes more.

    • If size is [0,12], memory allocated is 17.
    • If size is [13], memory allocated is 25.
    • If size is [20], memory allocated is 25.
    • If size is [21], memory allocated is 33.

提交回复
热议问题