指针常见错误总结

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

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++; //error
	free(p);
	
	return 0;
}

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




  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值