|
In addition to the method of allocating memory inside the function posted by LS, another idea is to allocate the memory area outside the function (that is, before the function call):
1. Allocate a memory area of SIZE size before the function call;
2. Pass the address and size of the memory buffer as parameters into the function, and the memory size used in the function as the return value, so the prototype of the function can be like this:
int foobar (void * in, void * out, int buffersize);
3. Inside the function we know how much memory we need:
If buffersize> = the required memory size, fill the result into the buffer;
If buffersize <the required memory size, the buffer remains unchanged, and the required memory size is returned as the return value;
4. Judge whether the operation is successful according to the transformation of the buffer. If it is unsuccessful, use the return value (the size of the memory required) to reallocate a sufficiently large memory area and call this function again.
5. After using the buffer, release the buffer
Compared with the function of allocating memory outside the function, the problem of who releases the memory allocated inside the function. |
|