JD> I am making a C DLL and have been wondering how I can tell if a passed
JD> pointer has enough memory allocated to have it carry back my string.
If you cannot control the API to your DLL, you can't. If you can control the
parameters, have the string (buffer) length available passed in.
JD> Do I have to just blindly reallocate just to make sure it has enough
JD> memory?
You can't do that for a number of reasons.
1. The pointer will not be returned. (Would be a big problem if #2 didn't
exist, and if the new memory from realloc is in a different place than the
old memory!)
2. The DLL has a different runtime library, thus different heap, than the
calling program, although they share the same stack. Memory created in the
EXE can only be realloc'ed or free'd by the EXE, and the same applies to each
DLL.
The solution I have used:
RET_TYPE foo(char* string, size_t string_len)
{
if (string_len < REQUIRED_STRING_LENGTH)
return RET_STRING_LENGTH_TOO_SHORT;
// code...
return RET_SUCCESS; // probably 0
}
Note that I do this both in DLL's and in EXE's... it is nice, consistant,
extendable, safe, clean, ...
Obviously, sometimes I don't know the required string length up front, or I
want to allow a shorter buffer to work when I don't need as much space, so I
have to check each concatenation(sp) before I add characters to make sure I
don't run out of space. If I would run out of space, I return the error
code, otherwise I continue.
HTH,
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)
|