[Mono-list] InteropServices: DllNotFoundException...?

Jonathan Pryor jonpryor@vt.edu
Sun, 23 May 2004 11:06:45 -0400


On Sun, 2004-05-23 at 10:56, Simon Ask Ulsnes wrote:
> >Furthermore, if you do something like this:
> >
> >	const char*
> >	get_my_string()
> >	{
> >		std::string s ("this is my string");
> >		return s.c_str();
> >	}
> >
> >You're *asking* for trouble, as the std::string destructor will free the
> >memory used to hold the string, so the string returned by
> >get_my_string() will be pointing to invalid memory.
> And guess what, that's actually what I'm doing (basically) - so far, it 
> works, I haven't detected any memory leaks (haven't checked very 
> thoroughly, though).
> But you say using marshalling and IntPtr's is the best way to do it?

The above situation isn't a memory leak, so it won't be detected as a
memory leak.  It's instead a "use after free".  It's akin to doing this:

	char *mem = malloc (20);                 // allocate
	strcpy(mem, "some string");              // initialize
	free (mem);                              // free
	printf ("this is my string: %s\n", mem); // use?!  bad.

It's not safe to use memory after it's freed.  Especially in a
multi-threaded environment -- the memory could have been re-allocated by
another thread and initialized with different data.

So this isn't a memory corruption bug or a memory leak, it's just bad
memory hygiene.

 - Jon