Other people's program core, segv_maperr. Check whether there is a problem with memory release. Just like the following code
# Include <stdio. h>
# Include <stdlib. h>
Void FreeMsgBuffer (char * msg)
{
If (NULL! = Msg)
{
Free (msg );
Msg = NULL;
}
}
Int main (void)
{
Char * pszTmp;
PszTmp = NULL;
PszTmp = (char *) malloc (sizeof (char) * 10 );
Strcpy (pszTmp, "leman ");
Printf ("name: % s \ n", pszTmp );
FreeMsgBuffer (pszTmp );
If (pszTmp = NULL)
{
Printf ("released \ n ");
// Other operations
}
Else
{
Printf ("memory content: % s \ n", pszTmp );
// Other operations
}
Return 0;
}
This problem has been considered before, that is, when passing a pointer to a function, you can change the content pointed to by the pointer through indirect access without changing the real parameter pointer itself (so passing a pointer is actually a value transfer ).
The solution to the problem is also very simple. Just pass a reference.
Void FreeMsgBuffer (char * & msg)
The function can change the reference itself, which is the real transfer of reference.
In the experiment, we found that we do not have enough understanding of the reference. For example, the following code displays the core at the delete. I can't explain why now, so I will leave it to study later.
Int main ()
{
Vector <int> v (100,0 );
Vector <int> & vf1 = * (new vector <int> ());
Vector <int> & vf2 = v;
Delete & vf1; // OK
Vf2 = * (new vector <int> ());
Delete & vf2; // core
Return 0;
}