C# app blocks when calling method from dll
<p>I'm currently exploring DLL exported functions and P/invoke in C#.
I've created very simple .dll:</p>

<p>Test.h</p>

<pre><code>#ifndef TEST_DLL_H
#define TEST_DLL_H
extern "C" __declspec(dllexport) const char * __cdecl hello ();
extern "C" __declspec(dllexport) const char * __cdecl test ();    
#endif  // TEST_DLL_H
</code></pre>

<p>Test.cpp</p>

<pre><code>#include &lt;stdlib.h&gt;
#include "test.h"
#include &lt;string.h&gt;

const char* hello()
{
    char *novi = (char *)malloc(51);
    strcpy(novi, "Test.");

    return novi;
}

const char * test()
{
    return "Test.";
}
</code></pre>

<p>I've compiled it and used in C# project like this:</p>

<pre><code>    [DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern IntPtr hello();

    [DllImport("test.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern string test();

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(test());
        IntPtr a =  hello();
        MessageBox.Show(Marshal.PtrToStringAnsi(a));
    }
</code></pre>

<p>But it isn't working. <code>test()</code> gets called successfully and I get back correct string. But <code>hello()</code> just hangs up the program. If I remove malloc line from the <code>hello()</code> definition and return constant, everything works, so I guess there's a problem with malloc that I'm now aware of.</p>

<p>Also, somewhere I've seen that string shouldn't be used when return type is char*. If that's true, why should we use IntPtr?</p>
