Summary of issues on dynamic memory allocation and string manipulation
#include <stdio.h> #include <stdlib.h>
#include <string.h>
#include <malloc.h>
Main ()
{
Char *p;
Char *q;
Char *w;
w= (char*) malloc (25*sizeof (char));
if (W==null) exit (1);
p= (char*) malloc (25*sizeof (char));
if (P==null) exit (1);
Q= (char*) malloc (10*sizeof (char));
if (Q==null) exit (1);
strcpy (P, "Dongbeidaxue");
Q= "Chenyujie";
printf ("%s\n", Q);
printf ("%s\n", p);
strcat (P,Q);
printf ("%s\n", p);
Free (w);
W=null;
Free (p);
P=null;
Free (q);
Q=null;
}
The program is very simple, but I have been debugging for a long time to understand;
The first is to distinguish between constant and dynamic regions;
Q= "Chenyujie", where Chenyujie is a constant, the first address of the constant is assigned to the pointer, assigned to the constant area of the first address, this block of memory is not allowed to modify, compared to the operation of P, the application of dynamic space, the use of strcpy function operation, the content is migrated to the dynamic zone, thereby again using strcat operation, succeeds. otherwise failed.
Summary is that the use of dynamic memory is based on the operation of the heap, is a continuous writable, the constant area can not be changed.