Verifying that memory was initialized in C

I wrote an API that requires context initialization and is then passed to every API call. The caller allocates memory for the context, and then passes it to the init functions with other parameters that describe how they want subsequent API calls to be made. The context is opaque, so the client cannot actually extinguish there; it is intended for internal use of API functions only.

The problem I am facing is that callers highlight the context but do not initialize it. As a result, subsequent API functions reference meaningless garbage, as if it were a real context.

I am looking for a way to verify that the context passed to the API function is actually initialized. I am not sure if this is possible. Two thoughts that I thought of are as follows:

  • Use a predefined constant and save it in the "magic" context field, which will be checked during the API call.
  • Use a checksum of the contents of the context by storing this in the "magic" field and checking it during the call.

Unfortunately, I know that either one of these parameters can lead to a false positive check, either because random shit in memory corresponds to a "magic" number, or because the context occupies the same space as the previously initialized context. I think the latter scenario is more likely.

Does it just boil down to the question of probability? In most cases, I can avoid false positives, but not all? Should I use a system that just gives me a reasonable probability of accuracy, or will it just make it difficult to debug other problems?

+5
source share
6 answers

, , . , . , , ( ) . , , , . , , .

typedef Context long;

typedef std::map<Context, InternalContext> Contexts;
Contexts _contexts;

Context nextContext()
{
  static Context next=0;
  return next++;
}

Context initialise()
{
  Context c=nextContext();
  _contexts.insert(make_pair(c, new InternalContext));
  return c;
}

void doSomethingWithContext(Context c)
{
  Contexts::iterator it=_ _contexts.find(c);
  if (it==_contexts.end())
    throw "invalid context";
  // otherwise do stuff with the valid context variable
  InternalContext *internalContext=*it.second;
}

, .

+3

, , create()/delete() API create . , , , create(), delete(), ( ) .

C, malloc'd, "", ; (, 8 ), . , create() .

, , delete(), malloc .

+6

. ( , nonce-number, ) , . , , API, .

, . :

/*
** Based on the tickets in qlib.c by Matt Bishop (bishop@ucdavis.edu) in
** Robust Programming.  Google terms: Bishop Robust Nonce.
** http://nob.cs.ucdavis.edu/~bishop/secprog/robust.pdf
** http://nob.cs.ucdavis.edu/classes/ecs153-1998-04/robust.html
*/

, .

+3

API, . API , , undefined.

+1

, , , , reset "" , , , , API. , , .

0

See what your system with an uninitialized mentor does. m $ does: Uninitialized memory blocks in VC ++

0
source

All Articles