-=> Quoting Darin McBride to John Dumas <=-
JD> I am making a C DLL and have been wondering how I
JD> can tell if a passed
JD> pointer has enough memory allocated to have it carry back my string.
DM> If you cannot control the API to your DLL, you can't. If you can
JD>
JD> For still learning programmers like myself the self made bug that
JD> drives me to distraction is intermittantly over filling or over
JD> reading an array or string.
JD>
JD> char string[4];
JD> string="OUCH";
You mean:
strcpy(string, "OUCH");
The operator = won't work here.
JD> I need a function put in C like.
JD> char string[4];
JD> if( CheckLimit( string,lenstr("OUCH"))
JD> ^^^^^^^^^^
JD> string="OUCH";
JD> else
JD> error;
Hmmm.. interesting, but not actually possible in C. What you _really_ need
is to move to C++ or Java. ;-)
JD> I guessing but since there is a free command the size of the
JD> variables must be held somwhere. Where?
Hmmm... couldn't be done. Let's use a few examples.
/* 1 - stack memory */
char s[20];
Actually, here we do know: sizeof(s)/sizeof(s[0]) This isn't helping to
prove my point, is it. :-)
/* 2 - heap memory */
char* s = malloc(some_num);
The memory allocation routines know how big s is. However, there is no way
of telling what it is otherwise.
For 3 & 4, assume we have a function:
size_t SayLength(char* s)
{
/* magic code */
}
/* 3 - heap memory */
char* s = malloc(some_num);
printf("%u", SayLength(s));
If SayLength is part of the library, it might be able to access the hidden
numbers...
/* 4 - stack memory */
char s[20];
printf("%u", SayLength(s));
What is the magic code supposed to do? Most (all?) compilers don't store the
sizes of the stack parameters (efficiency reasons) anywhere!
Worse yet, talking across CRTL's (C RunTime Library) is impossible - some of
these pointers may have been allocated on the stack (DLL uses EXE's stack),
or on the EXE's heap, or the DLL's heap, with malloc, with new (C++), with
your own memory management routines that use private, shared, virtual
memory... it just can't know.
Solution? Use the API style of passing in lengths when calling C functions,
or across RTLs (from EXE to DLL or DLL to EXE or DLL to DLL). Use growing
vectors or the string class type in C++.
---
---------------
* Origin: Tanktalus' Tower BBS (1:250/102)
|