Re: Access violation with heap memory
On Fri, 23 Jun 2006 19:50:09 +0500, "Adeel" <dontWantSpam@All> wrote:
Hi,
I'm getting a runtime access violation using heap memory that was
allocated in another function. The details follow...
I have a setup in which I pass a pointer to a secondary function (in
another dll) which allocates a buffer dynamically, populates it and
returns. Now, when I try to access the buffer in the main function, I
get a runtime access violation message. The code below will help
clarify this...
<CODE>
void fillBuf (char *p)
{
p = new char [10];
//fill the buffer
}
void useBuf ()
{
char *x = NULL;
fillBuf(x);
// access populated buffer
// e.g. char z = x[3]; //<< ACCESS VIOLATION
delete x;
}
</CODE>
I understand that this is probably bad design... 'new' and 'delete'
should happen in the same scope
Actually, new and delete rarely happen in the same scope, because a
destructor normally calls delete as part of the RAII idiom. Having a smart
pointer or other class manage dynamically allocated memory avoids memory
leaks and makes exception safety much easier to achieve. Note also that
you're using delete where you should be using delete[]; you must always
match new with delete and new[] with delete[].
but the problem is I don't know the
size of the buffer beforehand, so can't allocate it before the calling
the secondary function.
Now you might say I break the call down to two steps... use the first
to fetch the size, use the size to allocate the buffer, then issue the
second call to get it populated. But is there a way to do this in one
call?
Or alternatively, how would you design a solution to such a scenario?
I can think of passing a reference to a CArray object accross to the
secondary function...
Your current problem is that you are passing x by value to fillBuf, and the
caller doesn't observe the assignment to it. You can fix that by having
fillBuf use a reference parameter, in this case, a reference to a char*:
void fillBuf (char*& p) {...}
Now changes made through p affect the referent x as well.
but for some reason, I'm not entirely
comfortable with that... because later, there might be threads
involved in my program and I don't want to run into complications...
better stick with primitive types...
The use of primitive types doesn't avoid MT issues. I suggest you forget
about new[]/delete[] and use an array class like CArray or std::vector.
--
Doug Harrison
Visual C++ MVP