指针使用在c/c++中
指针在c/c++中非常强大 但是初学者使用经常带来一些错误 以下整理博主自己在开发过程中
存在的一些错误点
// 1. 存储数据时,越界
void test01()
{
// 1. 数组操作越界
char name[] = "googleyst";
printf("%c", name[100]);
// 2. 指针不断操作导致越界
char my_str[] = "hello world";
char *p_str = (char *)malloc(64);
for (int i = 0; i <= strlen(my_str); ++i)
{
*p_str = my_str[i];
p_str++;
}
free(p_str);
}
// 2. 返回局部变量的地址
int* test02()
{
int a = 10;
return &a;
}
// 3. 多次释放指针指向的空间
void test03()
{
char *p = malloc(sizeof(char) * 64);
free(p);
free(p);
}
// 4. 悬挂指针(野指针)
void test04()
{
char *name = malloc(64);
free(name);
//指针释放对应的内存空间后应当置空 否则造成野指针的情况
name = NULL;
}
// 5. 指针类型影响解引用操作
void test05()
{
// 指针的类型决定了指针的步长、解引用操作
int num = 100;
char *p_num = #
// 对 char * 类型的指针解引用无法获取数据
printf("%d", *p_num);
}
来源:CSDN
作者:googleyst
链接:https://blog.csdn.net/weixin_46048117/article/details/103603854