Dangling Pointer (ตัวชี้ล่าลง)
Dangling pointer คือ pointer ที่ชี้ไปยังตำแหน่งหน่วยความจำที่ถูกปล่อย (หรือลบ) แล้ว มีหลายวิธีที่ pointer กลายเป็น dangling pointer
Function Call (การเรียกฟังก์ชัน)
Pointer ที่ชี้ไปยังตัวแปร local จะกลายเป็น dangling เมื่อตัวแปร local ไม่ใช่ static
int *show(void) {
int n = 76; /* ... */
return &n;
}
ผลลัพธ์
Output of this program will be garbage address.
De-allocation of memory (การปล่อยหน่วยความจำ)
int main() {
float *p = (float *)malloc(sizeof(float));
// dynamic memory allocation.
free(p);
// after calling free() p becomes a dangling pointer
p = NULL;
// now p no more a dangling pointer.
}
Variable goes out of scope (ตัวแปรออกจากขอบเขต)
int main() {
int *p //some code//
{
int c; p=&c;
}
//some code//
//p is dangling pointer here.
}
Void Pointer (ตัวชี้แบบ Void)
Void pointer คือ pointer ที่ไม่เชื่อมโยงกับชนิดข้อมูลใดๆ มันชี้ไปยังตำแหน่งข้อมูลในที่เก็บ กล่าวคือ ชี้ไปยังที่อยู่ของตัวแปร เรียกอีกอย่างว่า general purpose pointer
มีข้อจำกัดบางประการ
- Pointer arithmetic ไม่สามารถทำกับ void pointer ได้เนื่องจากขนาดที่แน่นอน
- ไม่สามารถใช้เป็น dereferenced ได้
ตัวอย่าง
#include<stdlib.h>
#include<iostream>
using namespace std;
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
cout<<*( (int*) p)<<endl ;
p = &b;
cout<< *( (float*) p) ;
return 0;
}
ผลลัพธ์
7 7.600000
Algorithm
Begin
Initialize a variable a with integer value and variable b with float value.
Declare a void pointer p.
(int*)p = type casting of void.
p = &b mean void pointer p is now float.
(float*)p = type casting of void.
Print the value.
End.
Null Pointer (ตัวชี้ Null)
Null pointer คือ pointer ที่ไม่ชี้ไปที่ไหนเลย
การใช้งาน null pointer บางอย่าง -
เพื่อเริ่มต้นตัวแปร pointer เมื่อ pointer นั้นยังไม่ได้ถูกกำหนดที่อยู่หน่วยความจำที่ถูกต้อง
เพื่อส่ง null pointer ไปยัง argument ของฟังก์ชัน หากเราไม่ต้องการส่งที่อยู่หน่วยความจำที่ถูกต้อง
เพื่อตรวจสอบ null pointer ก่อนเข้าถึงตัวแปร pointer ใดๆ เพื่อให้เราสามารถจัดการ error ในโค้ดที่เกี่ยวกับ pointer ได้ เช่น dereference pointer เฉพาะเมื่อไม่ใช่ NULL
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int *p= NULL; //initialize the pointer as null.
cout<<"The value of pointer is ";
cout<<p;
return 0;
}
ผลลัพธ์
The value of pointer is 0.
Wild Pointer (ตัวชี้ Wild)
Wild pointers คือ pointer ที่ชี้ไปยังตำแหน่งหน่วยความจำ arbitrary (ไม่แม้แต่ NULL)
int main() {
int *ptr; //wild pointer
*ptr = 5;
}