Skip to content

Commit cc8642b

Browse files
Added on 07/10/23
1 parent 3f1fd3a commit cc8642b

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

CharArrayPointers.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int main(){
5+
char str[10] = "abcd";
6+
char *cptr = str; // same as char *cptr = &str[0], this works as str is char* type
7+
cout << cptr << endl;
8+
// char (*ch)[10] = &str; // char* ch = &str will give error as &str is char(*)[10] type
9+
// cout << *ch << endl;
10+
return 0;
11+
}

DanglingPointer.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
int *ptr = (int *)malloc(sizeof(int));
7+
free(ptr); // Now 'ptr' is a dangling pointer
8+
*ptr = 10; // Accessing memory through a dangling pointer is undefined behavior
9+
cout << *ptr << endl;
10+
return 0;
11+
}

WildPointer.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
int *ptr; // 'ptr' is a wild pointer because it is uninitialized
7+
*ptr = 10; // Accessing memory through a wild pointer is undefined behavior
8+
cout << *ptr << endl; // doesn't print anything as the memory is not allocated
9+
return 0;
10+
}

0 commit comments

Comments
 (0)