什么是野指针?(What is a wild pointer?)

时间:2022-09-05 18:39:44

未被初始化的变量称为野指针(wild pointer)。顾名思义,我们不知道这个指针指向内存中的什么地址,使用不当程序会产生各种各样的问题。

理解下面的例子:

int main()
{
int *p; // wild pointer, some unknown memory location is pointed *p = 12; // Some unknown memory location is being changed // This should never be done.
}

要注意的是,如果指针指向已知的变量就不是野指针。下面的代码中指针p在指向变量a之前一直是野指针。

int main()
{
int *p; // wild pointer, some unknown memory is pointed
int a = 10; p = &a; // p is not a wild pointer now, since we know where p is pointing *p = 12; // This is fine. Value of a is changed
}

如果我们需要指向一个没有变量名的值,我们应该给这个值分配内存,将这个值放在分配的内存中。

int main()
{
//malloc returns NULL if no free memory was found
int *p = malloc(sizeof(int)); //now we should check if memory was allocated or not
if(p != NULL)
{
*p = 12; // This is fine (because malloc doesn't return NULL)
}
else
{
printf("MEMORY LIMIT REACHED");
}
}