问题
Could someone explain what second parameter in realloc really is as I cant find a way to test it.
So suppose that we have something like this
int *p = malloc(sizeof(int)); //we have just enough space to store single int value
now if I want to store 2 int values in p do I need to send to realloc as second parameter 2 * sizeof(int)
new size of the block or sizeof(int)
as it needs to extend memory for size of int
In case I should send to realloc total value of new block in this case 2 * sizeof(int)
, what will it do in case I send it just sizeof(int)
, just return original pointer and do nothing within memory or something else?
回答1:
The second parameter is the new size of the memory block (total new size) in bytes. If you want room for 2 ints, you'd use 2 * sizeof(int)
.
just return original pointer and do nothing within memory or something else?
This is not guaranteed by the specifications. Many implementations will just return the original pointer unchanged, but they could just as easily move it. You will not get a new memory allocation large enough for 2 ints, however, merely the original data values in a memory location large enough for sizeof(int)
.
回答2:
You want to tell realloc the new total size of the allocation. So from your example, 2 * sizeof(int)
.
Your second question isn't entirely clear, so I'll try to wrap all those pieces into one sentence. If you call realloc with the same size value as the original call to malloc, it is up to the implementation whether to return the original pointer or to move the data to a (implementation-defined) more convenient place; if you then try to store two int
s in the space for which you only requested one int
then you've triggered undefined behavior. It could clobber other allocated memory (causing wrong results in calculations) or (more likely) it could clobber malloc's own bookkeeping data (likely your program will abort with a Segfault somewhat later on when malloc actually takes a look at the data.
来源:https://stackoverflow.com/questions/10526314/c-realloc-what-does-size-really-mean