The C language copies the string malloc, And the C language string malloc.
Today, I am reading the code of my predecessors. Sometimes, copying strings directly assigns pointers to another pointer, some malloc a memory, and then copy the entire string value, which is a bit confusing, after studying it, I found that there are no mysteries. It is actually very simple, but it is better to record it. Conclusion: if the memory of the source string to be copied is recycled, malloc must be used to copy the entire string. (sometimes malloc is used to prevent the source string from being modified, but do not consider this factor). If it is not recycled, it will not be used. The following is the test code.
# Include <stdio. h>
# Include <string. h>
Typedef void (* str_cpy_slk) (char * name );
Void test (str_cpy_slk cb );
Void call_back (char * name );
Char * test_name = NULL;
Int main (void)
{
Test (call_back );
Printf ("name: % s \ n", test_name );
Return 0;
}
Void test (str_cpy_slk cb)
{
Char myname [8] = {0 };
Snprintf (myname, sizeof (myname), "% s", "slk ");
Printf ("myname: % s \ n", myname );
Cb (myname );
}
Void call_back (char * name)
{
Test_name = name;
Printf ("test_name: % s \ n", test_name );
}
Cannot be displayed. Use malloc to open up memory. If you assign a value, you can
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
Typedef void (* str_cpy_slk) (char * name );
Void test (str_cpy_slk cb );
Void call_back (char * name );
Char * test_name = NULL;
Int main (void)
{
Test (call_back );
Printf ("name: % s \ n", test_name );
Free (test_name );
Return 0;
}
Void test (str_cpy_slk cb)
{
Char myname [8] = {0 };
Snprintf (myname, sizeof (myname), "% s", "slk ");
Printf ("myname: % s \ n", myname );
Cb (myname );
}
Void call_back (char * name)
{
Test_name = (char *) malloc (strlen (name) + 1 );
Snprintf (test_name, strlen (name) + 1, "% s", name );
Printf ("test_name: % s \ n", test_name );
}