指针常见错误总结

来源:互联网 发布:linux启动数据库命令 编辑:程序博客网 时间:2024/05/17 04:50

记录遇到过的关于指针的错误与疑惑。

1.未初始化,就赋值。

  int *p;  *p = 1;

运行时出现段错误,因为系统没有给指针p分配内存。没有房子,娶了媳妇往哪里放啊。

 int *p = (int*)malloc(sizeof(int*));//先买房 *p = 1;//再结婚

2.误用指针操作常量。

字符串,是一个常量,存储在数据区的常量段,可以访问,但不能修改。可远观而不可近玩焉。

char *p = "123456";printf("a=%c\n",*(p+1));*(p+2) = 8; //段错误

3.把指针当形参,是值传递,不会改变原指针的值。

#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory( char *p) {    /* p是形参,str的值赋给p*/    p = (char*)malloc(10*sizeof(char));    /*malloc()返回一个随机值,所以p有了新的值,而str的值不变。*/    printf("p=%p\n",p);    strcpy(p, "fuck.");}int main(void){    char *str = NULL;    printf("before getmemory(),str=%p\n",str);    getmemory(str);    printf("str=%s\n", str);//str依然为null    free(str);    return 0;}

4.把二级指针当形参,传递指针的地址,会改变原指针的值。

#include <stdio.h>#include <string.h>#include <stdlib.h>void getmemory( char **p) {    /* 用一个二级指针p指向指针str,通过*p来操作str的值。*/    *p = (char*)malloc(10*sizeof(char));    printf("*p=%p\n",*p);    strcpy(*p, "fuck.");}int main(void){    char *str = NULL;    printf("before getmemory(),str=%p\n",str);    getmemory(&str);//传递str的地址    printf("str=%p\nstr:%s\n", str,str);//str的值被改变    free(str);    return 0;}


5.free一个被移动了的指针

#include <stdio.h>#include <stdlib.h>int main(){char *p = (char*)malloc(10 * sizeof(char));if (NULL == p){printf("malloc error.\n");return -1;}p++; //errorfree(p);return 0;}

p 被移动过了,free时会出错。




0 0
原创粉丝点击