内存主要有四块,栈,堆,全局和静态,常量。
栈,堆和java一样,开发主要是集中在堆里,能过new,malloc来操作,其它内存都是系统申请释放的。
关于常量如果用指针修改会报段错误:
char* charP1 = "test const"; *(charP1+1) = 'c'; cout << charP1 << endl;
堆操作:
#include <iostream> #include<stdlib.h> using namespace std; void test(string &str); void test(char* charP); void getPos(); int main() { // stack string str = "abcdefghijk"; test(str); // error: type 'struct std::string' argument given to 'delete', expected pointer // str没有用new分配的是heap空间,数据在stack中,超出作用域自动释放,手动删除会报错 // 看错误提示,delete后需要跟指针,所以只能delete new返回的 //delete str; cout << str << endl; // heap string* str1 = new string(); *str1 = "abcdefghijk"; test(*str1); cout << *str1 << " str1 address:" << (void*)str1 << endl; // new分配的heap空间,不删除会内存泄露 // 删除后可以看到&pos = str1; delete str1; str1 = NULL; getPos(); int mallSize = 10; char* str2 = (char*)malloc(mallSize * sizeof(char)); memset(str2, 0x00, mallSize); strcpy(str2, "abcdef"); test(str2); cout << str2 << endl; free(str2); return 0; } void test(string &str) { int size = str.size(); cout << size << endl; char* charP = new char[str.size() + 1]; memset(charP, 0x00, str.size() + 1); for (int i = 0; i < str.size(); i++) { *(charP + str.size() - i - 1) = *(str.c_str() + i); } //memcpy(charP, str.c_str(), str.size()); //string &r = str; //cout << (void*) charP << endl; //r = charP; str = charP; delete[] charP; charP = NULL; cout << "return: " << (void*) charP << endl; } void test(char* charP) { char* tmpP = new char[strlen(charP)]; strcpy(tmpP, charP); for (int i = 0; i < strlen(charP); i++) { *(charP + strlen(charP) - i - 1) = *(tmpP + i); } delete[] tmpP; } void getPos() { char* pos = new char[1]; *pos = 0; cout << "pos address:" << (void*)pos << endl; }