首页  

c语言中常见的内存错误     所属分类 c 浏览量 680
常见的内存错误      

内存分配失败,仍然使用 

引用尚未初始化的指针

越界操作内存

没有释放内存,造成内存泄漏

释放的内存继续使用
返回了“栈内存的指针或引用”,因为堆栈中的变量在函数结束后自动销毁
内存free后,指针未设置为NULL,导致 野指针

使用malloc申请内存时,检查相对应的指针是否为NULL
使用前初始化 
数组或指针下标越界
动态内存的申请和释放配对,防止内存泄漏
free后,将指针设置为NULL,避免野指针


几个概念 野指针 指指向“垃圾”内存的指针 指针变量没有初始化 ,创建指针变量时,置为NULL或指向合法的内存单元 free之后,没有置为NULL 指针跨越合法范围操作 不要返回指向栈内存的指针或引用
https://gitee.com/dyyx/hellocode/blob/master/web/tech/c/demo/memory001.c linux gcc -std=c99 memory001.c MAC gcc memory001.c #include "stdio.h" #include "stdlib.h" #include "string.h" char *GetString1() { char p[] = "hello world!"; // linux 警告:函数返回局部变量的地址 [-Wreturn-local-addr] // MAC warning: address of stack memory associated with local variable 'p' returned [-Wreturn-stack-address] return p; } char *GetString2(void) { char *p = "hello world!"; //指针变量p在栈区,指向常量区的字符 return p;//ok,返回字符串的地址 } char* GetMemory(int num) { char *p = (char *)malloc(sizeof(char) * num); return p ;//ok,返回堆区的地址 } void useAfterFree(){ char *pstr = (char *)malloc(sizeof(char)*100); free(pstr); printf("%p\n",pstr); if (NULL !=pstr) { // free之后 未置为NULL ,继续使用 strcpy(pstr,"hello"); printf("%s\n",pstr); } } void leak() { char *p = NULL; for ( int i = 0; i<10; i++) { // LINUX 错误:只允许在 C99 模式下使用‘for’循环初始化声明 // mac ok p = (char*)malloc(100); } printf("%p\n",p); strcpy(p,"hello"); printf("%s\n",p); free(p); } void overflow(){ char str[10]; strcpy(str,"hello world!"); printf("%s\n",str); } int main(){ printf("hello\n"); // MAC , warning: address of stack memory associated with local variable 'p' returned char * p = GetString1(); printf("%p\n",p); p = GetString2(); printf("%p\n",p); p = GetMemory(1000); printf("%p\n",p); free(p); p = NULL; useAfterFree(); leak(); // MAC Illegal instruction: 4 // Linux 段错误 overflow(); return 0; }

上一篇     下一篇
C++面向对象知识点

c++构造函数

C++ this 指针

c++运算符优先级和结合性

编译时指定宏参数

systemctl service chkconfig 之间的关系