Determine size of dynamically allocated memory in C

后端 未结 15 2504
孤街浪徒
孤街浪徒 2020-11-22 06:15

Is there a way in C to find out the size of dynamically allocated memory?

For example, after

char* p = malloc (100);

Is there

15条回答
  •  故里飘歌
    2020-11-22 06:45

    I was struggling recently with visualizing the memory that was available to write to (i.e using strcat or strcpy type functions immediately after malloc).

    This is not meant to be a very technical answer, but it could help you while debugging, as much as it helped me.

    You can use the size you mallocd in a memset, set an arbitrary value for the second parameter (so you can recognize it) and use the pointer that you obtained from malloc.

    Like so:

    char* my_string = (char*) malloc(custom_size * sizeof(char));
    if(my_string) { memset(my_string, 1, custom_size); }
    

    You can then visualize in the debugger how your allocated memory looks like:

提交回复
热议问题