Why does `free` in C not take the number of bytes to be freed?

前端 未结 12 1614
情歌与酒
情歌与酒 2020-12-12 20:11

Just to be clear: I do know that malloc and free are implemented in the C library, which usually allocates chunks of memory from the OS and does it

12条回答
  •  春和景丽
    2020-12-12 20:34

    Well, the only thing you need is a pointer that you'll use to free up the memory you previously allocated. The amount of bytes is something managed by the operating system so you don't have to worry about it. It wouldn't be necessary to get the number of bytes allocated returned by free(). I suggest you a manual way to count the number of bytes/positions allocated by a running program:

    If you work in Linux and you want to know the amount of bytes/positions malloc has allocated, you can make a simple program that uses malloc once or n times and prints out the pointers you get. In addition, you must make the program sleep for a few seconds (enough for you to do the following). After that, run that program, look for its PID, write cd /proc/process_PID and just type "cat maps". The output will show you, in one specific line, both the beginning and the final memory addresses of the heap memory region (the one in which you are allocating memory dinamically).If you print out the pointers to these memory regions being allocated, you can guess how much memory you have allocated.

    Hope it helps!

提交回复
热议问题