Problem Introduction:
A previous default error was found during the internship, and the same char *c = "abc" and Char c[]= "ABC", which changed the
The tolerance program will crash, and the latter is completely correct.
Program Demo:
Test environment devc++
Code
#include <iostream>
using namespace std;
main()
{
char *c1 = "abc";
char c2[] = "abc";
char *c3 = ( char* )malloc(3);
c3 = "abc";
printf("%d %d %s\n",&c1,c1,c1);
printf("%d %d %s\n",&c2,c2,c2);
printf("%d %d %s\n",&c3,c3,c3);
getchar();
}
Run results
2293628 4199056 ABC
2293624 2293624 ABC
2293620 4199056 ABC
Resources:
The first thing to figure out is the partitioning of the memory that the compiler uses:
First, the preparation of knowledge-Program memory allocation
The memory used by a program compiled by C + + is divided into the following sections
1, stack area (stack)-by the compiler automatically assigned to release, store the function of the parameter values, local variables and other values. It operates in a manner similar to
The stack in the data structure.
2, heap area (heap)-Generally by the programmer assigned to release, if the programmer does not release, the program at the end may be reclaimed by the OS. Note that it is different from the heap in the data structure, the distribution is similar to the list, hehe.
3, Global zone (static area) (static)-the storage of global variables and static variables is placed in a piece, the initialization of global and static variables in a region, uninitialized global variables and uninitialized static variables in another adjacent area. The system is released after the program is finished.
4, literal constant area-the constant string is here. The system is released after the program is finished.
5. Program code Area
This is written by a predecessor, very detailed
//main.cpp
int a=0; //全局初始化区
char *p1; //全局未初始化区
main()
{
int b;栈
char s[]="abc"; //栈
char *p2; //栈
char *p3="123456"; //123456\0在常量区,p3在栈上。
static int c=0; //全局(静态)初始化区
p1 = (char*)malloc(10);
p2 = (char*)malloc(20); //分配得来得10和20字节的区域就在堆区。
strcpy(p1,"123456"); //123456\0放在常量区,编译器可能会将它与p3所向"123456"优化成一个
地方。
}