Determine size of dynamically allocated memory in C

后端 未结 15 2499
孤街浪徒
孤街浪徒 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:43

    Well now I know this is not answering your specific question, however thinking outside of the box as it were... It occurs to me you probably do not need to know. Ok, ok, no I don't mean your have a bad or un-orthodox implementation... I mean is that you probably (without looking at your code I am only guessing) you prbably only want to know if your data can fit in the allocated memory, if that is the case then this solution might be better. It should not offer too much overhead and will solve your "fitting" problem if that is indeed what you are handling:

    if ( p != (tmp = realloc(p, required_size)) ) p = tmp;
    

    or if you need to maintain the old contents:

    if ( p != (tmp = realloc(p, required_size)) ) memcpy(tmp, p = tmp, required_size);
    

    of course you could just use:

    p = realloc(p, required_size);
    

    and be done with it.

提交回复
热议问题