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
#include <stdlib.h>
#include <stdio.h>
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 pointer ใน C คือ pointer ที่ไม่เชื่อมโยงกับชนิดข้อมูลใดๆ มันชี้ไปยังตำแหน่งข้อมูลในที่เก็บ กล่าวคือ ชี้ไปยังที่อยู่ของตัวแปร เรียกอีกอย่างว่า general purpose pointer
มีข้อจำกัดบางประการ
Pointer arithmetic ไม่สามารถทำกับ void pointer ได้เนื่องจากขนาดที่แน่นอน
ไม่สามารถใช้เป็น dereferenced ได้
ตัวอย่างง่ายๆ
#include<stdlib.h>
int main() {
int a = 7;
float b = 7.6;
void *p;
p = &a;
printf("Integer variable is = %d", *( (int*) p) );
p = &b;
printf("\nFloat variable is = %f", *( (float*) p) );
return 0;
}
ผลลัพธ์
Integer variable is = 7 Float variable is = 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 pointer คือ pointer ที่ไม่ชี้ไปที่ไหนเลย การใช้งาน null pointer บางอย่าง:
เพื่อเริ่มต้นตัวแปร pointer เมื่อ pointer นั้นยังไม่ได้ถูกกำหนดที่อยู่หน่วยความจำที่ถูกต้อง
เพื่อส่ง null pointer ไปยัง argument ของฟังก์ชัน หากเราไม่ต้องการส่งที่อยู่หน่วยความจำที่ถูกต้อง
เพื่อตรวจสอบ null pointer ก่อนเข้าถึงตัวแปร pointer ใดๆ เพื่อให้เราสามารถจัดการ error ในโค้ดที่เกี่ยวกับ pointer ได้ เช่น dereference pointer เฉพาะเมื่อไม่ใช่ NULL
ตัวอย่าง
#include<iostream>
#include <stdio.h>
int main() {
int *p= NULL;//initialize the pointer as null.
printf("The value of pointer is %u",p);
return 0;
}
ผลลัพธ์
The value of pointer is 0.
Wild Pointer
Wild pointers คือ pointer ที่ชี้ไปยังตำแหน่งหน่วยความจำ arbitrary (ไม่แม้แต่ NULL)
int main() {
int *ptr; //wild pointer
*ptr = 5;
}