Use of realloc Functions
# Include <stdio. h> # include <stdlib. h> # include <iostream> using namespace STD; void setval (char * TMP, int QS, int num, char mm) {for (INT I = QS; I <num-1; I ++) {* (TMP + I) = mm;} * (TMP + num-1) = '\ 0';} int main () {char * P, * q; // shorten memory P = (char *) malloc (1000); setval (p, 800, 'A'); q = (char *) realloc (p ); if (Q! = NULL) {setval (Q, 795,800,'s '); cout <q <Endl; cout <"success" <Endl;} else {setval (p, 500,800, 'F'); cout <"fail" <Endl;} Free (Q); getchar (); System ("pause "); return 0 ;}
Realloc can expand or contract the space indicated by the given pointer, And the content in the original memory will remain unchanged. Of course, for downgrading, the contents of the reduced part will be lost.
Realloc does not guarantee that the adjusted memory space is the same as the original memory space. On the contrary, the pointer returned by realloc is likely to point to a new address:
Because realloc allocates memory from the stack, when a memory space is extended, realloc directly obtains additional bytes from the bytes following the existing data on the stack; however, if the number of bytes after the data is not enough, the first free block with sufficient size on the stack will be used, and the existing data will be copied to the new location, the old block is put back on the stack.
In the code,
If we use the I = (int *) realloc (I, 2 * sizeof (INT) re-allocate memory mode, there are two situations:
1. If the allocation is successful and the void * pointer is returned: If the value returned by realloc is different from that returned by malloc, the old memory to which I points is automatically free after the realloc function is completed.
2. If the allocation fails, the return value is null. At this time, the memory that I originally pointed to has not been free, but the address is not found yet, so Memory Leak appears.
Solution: Define another pointer J to receive the realloc return value and determine whether it is successful. If yes, J is assigned to I.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/leopardaa521/archive/2009/10/12/4658887.aspx