Summary of issues on dynamic memory allocation and string manipulation

Source: Internet
Author: User
Tags constant

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.