Is it good coding practice to assign the address returned by realloc() to the same pointer?

前端 未结 2 989
广开言路
广开言路 2021-01-15 05:43

I saw some code related to realloc() on some sites as below.

int *p = (int *)malloc(sizeof(int) * 10);
p = (int *)realloc(p, 100);

But as t

2条回答
  •  孤城傲影
    2021-01-15 06:06

    R. gave a clear answer to your question. Let me emphasize two other issues in the code fragment:

    int *p = (int *)malloc(sizeof(int) * 10);
    p = (int *)realloc(p, 100);
    

    It is mostly considered bad practice in C to cast the return value of malloc(), calloc() and realloc(). The void * return value will automatically be converted to the appropriate pointer type, unless the code is compiled as C++ code, which is an estranged cousin of C.

    More importantly, it does not make sense to realloc the pointer to a hardcoded size 100. The number of ints that will be accessible in the reallocated array will depend on the actual size of the int type, which can vary from one system to another. Indeed on some architectures, 100 is not even a multiple of sizeof(int). The author might have meant to write p = realloc(p, sizeof(int) * 100); or p = realloc(p, sizeof(*p) * 100);, and more context around the fragment could help understand the intent... As written, it is very likely a bug, for multiple reasons.

提交回复
热议问题