int* ptr = NULL; //Is this going to avoid the problem

This will cause ptr to point to NULL which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour.

The main advantage is your convenience for checking whether the ptr has or has not been initialized to anything, ie:

 if (ptr != NULL)
 {
     // assume it points to something
 }

Since this is pretty idiomatic, its pretty dangerous to not initialize the pointer to NULL. The pointer would be initialized to a non-NULL garbage value that doesn't really point to anything real. Worst of all, the check above would pass, causing even worse problems if it just so happens that the address in the pointer is memory you can legally access. In some Embedded environments, you might be able to access any part of memory, so you might accidentally corrupt random parts of memory or random parts of your executing code.

Answer from Doug T. on Stack Overflow
🌐
Sanfoundry
https://sanfoundry.com › c-tutorials-uninitialized-illegal-pointer-indirection-illegal-pointer
What is an Uninitialized or Illegal Pointer in C? - Sanfoundry
December 31, 2025 - An uninitialized pointer is a pointer that has been declared but not assigned a specific memory address. Using such a pointer leads to undefined behavior because it may point to an arbitrary memory location.
Discussions

What Does It Mean to Specify a Data Type for an Uninitialized Pointer?
Depends on how your platform specifically implements pointer variables. On most modern platforms a “pointer” is just a 32- or 64-bit unsigned integer that directly holds a virtual memory address. If not explicitly initialized, a pointer variable would contain some random address value. Attempting to dereference such a pointer has undefined behavior. More on reddit.com
🌐 r/C_Programming
10
2
July 17, 2024
c - Difference between uninitialized and null pointer - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Is there any difference between null pointer and uninitialized pointer? More on stackoverflow.com
🌐 stackoverflow.com
values of uninitialized pointers in C - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... We can clairly see the memory adress of d but both p, t and c don't look like adresses. I used to think that a uninitialized pointer takes the Null value after its declaration. More on stackoverflow.com
🌐 stackoverflow.com
Is there a use for uninitialized pointers in C or C++? - Stack Overflow
In one of the comments in this question, it was brought out that initializing C++ pointers by default would break compatibility with C. That's fine, but why would something like this matter? I wo... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is the difference between a NULL pointer and an uninitialized pointer?
A NULL pointer definitely points at nothing, and you can test for it. An uninitialized pointer holds whatever bytes happened to be in that memory - possibly a valid-looking address - so there is no test that can catch it. Always initialize pointers to NULL when you have nothing better.
🌐
coddy.tech
coddy.tech › docs › null pointers
Runnable C Docs: NULL Pointers | Coddy
What is a NULL pointer in C?
A pointer holding the null pointer constant - a value guaranteed to compare unequal to the address of any real object. It is the standard way to say "this pointer points at nothing yet", and NULL is the macro for it, defined in and several other headers.
🌐
coddy.tech
coddy.tech › docs › null pointers
Runnable C Docs: NULL Pointers | Coddy
What happens if you dereference a NULL pointer in C?
It is undefined behavior. In practice, on desktop and server systems, it crashes immediately with a segmentation fault because address zero is deliberately left unmapped. On embedded systems without memory protection it may silently read or corrupt something instead, which is far worse.
🌐
coddy.tech
coddy.tech › docs › null pointers
Runnable C Docs: NULL Pointers | Coddy
🌐
Reddit
https://reddit.com › r/c_programming › why does using an uninitialized pointer to a structure work?
r/C_Programming on Reddit: Why does using an uninitialized pointer to a structure work?
March 8, 2024 -

I have a structure like this:

struct foo {
	int x;
	char y;
};

And this is my code in main():

struct foo *p; //haven't initialized it/used malloc
p->x = 10; //gives a warning but not an error?
p->y = 'a';
	
printf("%d %c\n",p->x,p->y); //why does this give an actual output???
printf("%p %p %p\n",p,&(p->x),&(p->y)); 
//this returns d0, d0, d4, like it would for a properly allocated struct (removed the rest of the memory address for conciseness)

So why does using an uninitialized or unallocated pointer to a struct make any sense?

(My compiler is gcc)

Edit: Thanks for all the responses, you guys are really helpful!

🌐
GeeksforGeeks
https://geeksforgeeks.org › c language › dangling-void-null-wild-pointers
Dangling, Void , Null and Wild Pointers in C - GeeksforGeeks
July 11, 2026 - It can be avoided by initializing pointers to NULL or assigning them a valid memory address before use. ... #include <stdio.h> int main() { int *ptr; // Wild pointer (uninitialized) printf("The pointer is declared but not initialized.\n"); // ...
🌐
Salivity
https://salivity.github.io › c › article › how-uninitialized-pointers-cause-crashes-in-c
How Uninitialized Pointers Cause Crashes in C - c
In the C programming language, uninitialized pointers—often referred to as "wild pointers"—are a primary source of erratic software failures, security exploits, and difficult-to-reproduce bugs.
Find elsewhere
🌐
Coddy.Tech
https://coddy.tech › docs › null pointers
Runnable C Docs: NULL Pointers | Coddy
September 18, 2026 - A null pointer tests as false in a condition and a valid pointer as true, so both work. The explicit form reads better when a stranger is scanning your code for bugs. Three distinct situations that beginners blur together: int *a = NULL; "points at nothing" - testable, safe to check int *b; uninitialized - holds garbage, NOT testable int *c = &x; points at a real object
🌐
Reddit
https://reddit.com › r/c_programming › what does it mean to specify a data type for an uninitialized pointer?
r/C_Programming on Reddit: What Does It Mean to Specify a Data Type for an Uninitialized Pointer?
July 17, 2024 -

Hey there everyone,

I am quite new to programming, so sorry if this may sound stupid.

When defining a pointer, we have to specify its data type, like this:

int *pointer;

This just means that my pointer is intended to point to an int data type. Now, let’s say I create a new data type but don’t use it anywhere else, like this:

typedef struct node
{
    int number;
    struct node *next;
} node;

Now that I have specified a data type called node, I won't specifically use it anywhere in my code. So, I wanted to know what would happen with something like this:

node *pointer;

From my understanding, since this pointer is uninitialized, it would just point to somewhere random. However, I have told it that this pointer is intended to point to a node. Since it is uninitialized, there is no way it would actually point to a valid node.

So, from a low-level perspective, what is actually happening here?

Top answer
1 of 7
9
Depends on how your platform specifically implements pointer variables. On most modern platforms a “pointer” is just a 32- or 64-bit unsigned integer that directly holds a virtual memory address. If not explicitly initialized, a pointer variable would contain some random address value. Attempting to dereference such a pointer has undefined behavior.
2 of 7
4
You can print out pointers, so you can try it. For example, let's declare an array of 20 uninitialized pointers to struct node and see what those pointers contain: $ cat testit.c #include struct node { int number; struct node *node; }; int main(int argc, char *argv[]) { struct node *n[20]; for (int i = 0; i < 20; i++) printf("n[%d] = %p\n", i, (void *) n[i]); return 0; } $ gcc -o testit testit.c $ ./testit n[0] = (nil) n[1] = (nil) n[2] = (nil) n[3] = (nil) n[4] = (nil) n[5] = (nil) n[6] = (nil) n[7] = (nil) n[8] = (nil) n[9] = (nil) n[10] = 0x5599d7059040 n[11] = 0xf0b5ff n[12] = 0xc2 n[13] = 0x7ffdac4c2267 n[14] = 0x7ffdac4c2266 n[15] = 0x5599d705a24d n[16] = 0x7fbbd3c762e8 n[17] = 0x5599d705a200 n[18] = (nil) n[19] = 0x5599d705a080 $ So, a bunch of them are (nil) (means NULL), and a bunch of them contain garbage. If I run the program a 2nd time, I get similar, but not exactly the same results. Some of the garbage values are different. Basically, no telling what an uninitialized variable on the stack or on the heap will contain, could be anything. (static storage class variables will get zeroed by default though.)
🌐
HowStuffWorks
https://computer.howstuffworks.com › tech › computer software › programming
Pointers: Common Bugs - The Basics of C Programming | HowStuffWorks
March 8, 2023 - An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. One way to create this error is to say p=q;, when q is uninitialized.
🌐
LabEx
https://labex.io › tutorials › c-how-to-check-uninitialized-pointer-risks-420065
How to check uninitialized pointer risks | LabEx
By understanding these fundamental concepts, you'll be well-prepared to explore more advanced pointer techniques in LabEx's C programming courses. An uninitialized pointer is a pointer that has not been assigned a valid memory address.
🌐
Medium
https://medium.com › @pkgmalinda › mastering-pointers-in-c-declaration-initialization-and-the-danger-of-uninitialized-d99c81975165
🧭 Mastering Pointers in C++: Declaration, Initialization, and the Danger of Uninitialized Pointers 💥 | by Malinda Gamage | Medium
February 6, 2025 - It makes it easier to spot the pointer variable. Now comes the serious part. 😰 An uninitialized pointer contains garbage data — a random address in memory. You have no idea where it’s pointing or what it’s messing with.
Top answer
1 of 10
17

This is a very specialized optimized case for Video Games (basically an embedded system). We used to use them for Load-In-Place data behavior in our Video Games to speed up loading (and avoid fragmentation).

Basically we would create console-side (Playstation) objects in a PC cooker. Then to reduce fragmentation overload, we would pack the data objects in a contiguous buffer with a single alloc. References to the data objects in this buffer would then be changed to subtract the base from pointers to offsets (unfix call -- we also had a virtual fix / unfix calls that took the buffer base and could convert between offsets and pointers).

When we loaded the data, it loaded in one large block. All data referenced by the root was off the root object. We could do an inplace "new" on the the root that would initialize the proper VF tables for the object and fixup all the attached blocks (by doing inplace new and then fixing up attached blocks respectively).

We needed the constructors called (in place new) to generate the proper VF-Tables in the objects. However, if the pointers were automatically cleared to NULL during the constructor, we would have lost the offset data and not been able to recreate the pointers between the objects within the contiguous block.


FWIW, this is a common technique in the Video Game world. This Gamasutra article (not written by me or my coworkers) explains in detail the similar thing they did at another company:

Also, this topic of discussion on SourceForge.

There have even been several GDC (Game Developer Conference) talks on the subject.

Searching on Google for "load-in-place" will give many other examples of people using this technique that basically requires uninitialized pointers.


NOTE: Currently, this is the only response that actually answers the question asked ("Is there a use for uninitialized pointers in C or C++?") by giving a specific use for pointers that must remain unitialized.

All the other responses are better answers for the original question referenced ("[C++] Why aren’t pointers initialized with NULL by default?") that caused the poster to ask this question.

2 of 10
11

First of all, initializing pointers (or any other variables) by default does not break compatibility with C. Both C and C++ state that a value of uninitialized variable is indeterminate; in practice, this means that it can hold any value (including a trap representation), but note that 0 belongs to the set of "any values"! So a conformant implementation can perfectly well initialize all pointers to 0. Your program, should it rely on that, would not be conformant, however.

Now as to why you may want your pointer to not be initialized: mainly when it is written to afterwards. For example:

void foo(int*& p) {
   p = new int;
}

int* p; // why initialize? we overwrite it anyway
foo(p);

You can say that compiler should be able to optimize this away. Unfortunately, it cannot do so if the definition of foo is not available (e.g. global link-time optimizations are disabled; or they are enabled, but the function is in a DLL), since it doesn't know if foo will try to read from p (and then initialization would be needed), or if it would just write to it (and then initialization isn't needed). What more, there may be cases that are harder to analyze; for example:

bool try_parse_int(const char* s, int& n)
{
    // if parsed successfully, assign result to n and return true
    // if there was error parsing, don't touch n and return false
    ...
}

int n;
if (try_parse_int(s, n)) {
    // use n here
    ...
} else {
   // don't use n here
   ...
}

This one is much harder for the compiler to analyze even if it has full definitions of all functions.

🌐
Unstop
https://unstop.com › home › blog › null pointer in c | a detailed explanation with examples
Null Pointer In C | A Detailed Explanation With Examples
May 3, 2024 - Uninitialized Pointers: If a pointer is declared but not initialized to point to a valid memory address, it will hold a garbage value, which could be interpreted as a null pointer in C.
🌐
Reddit
https://reddit.com › r/c_programming › how can i pass an un-initialized pointer as an argument to a function in c?
r/C_Programming on Reddit: How can I pass an un-initialized pointer as an argument to a function in C?
February 6, 2022 -

How can I initialize a pointer from a function using malloc()?

I'm trying to make an API for rendering HTML in a window using C. The usage will look somewhat like this:

parseHTMLFromString(element* root, char* html);

int main()
{
    char* html = "<button>click on this <b>bold</b> text</button>"
    element* root;
    
    parseHTMLFromString(root, html);
}

The problem is that when the *root variable is passed as an uninitialized pointer, any acess to it causes a segmentation fault (even if I am accessing it to initialize). I know that if I initialize root using malloc the error will go away, but I want to avoid forcing the user to do that for the API to work. if this is impossible, I'l just tell the user to initialize if in the API's documentation, but I would rather make it work like this.

I hope this question isn't too easy for this subs standards (some people here say they made OPERATING SYSTEMS!!!), but the reason I wanted to avoid StackOverflow is because most of the people answering C-related questions there are super toxic to relatively easy questions from new accounts, and my account is new because my old one got banned from the stupid site due to downvotes.

Top answer
1 of 4
26
Pass a pointer to the pointer. If your original pointer is p, and you pass &p as a function argument, then the function can dereference that to initialise the original pointer: int element_new(element **e) { assert(e); *e = malloc(sizeof **e); if (!*e) return -errno; **e = (element){ .foo = 42, .bar = 123, }; return 0; }
2 of 4
3
Firstly, your html string should be "const char*" since (I assume) the semantics of your parse function are such that it doesn't -- and in fact *cannot* change that string. You want callers to be able to rely on this. [Apologies if you haven't learned about const yet!] I disagree with some of the advice you're being given here. It's generally not a best practice to malloc inside a function and expect the caller to free the memory. It's entirely possible that two different bodies of code end up using two different heap implementations. One example is if your parse function is inside a dynamically loaded library (DLL on Windows) -- it may have its own copy of the C runtime and therefore the caller could be trying to free() blocks that were malloc'ed from a different heap! There are various ways to deal with this issue. An easy one would be to require the caller to pass in the address of an allocator function. Also, you didn't show us what your element struct looks like... does it have pointers to other element instances, or other similar complexities? If so, then simply allocating space for one instance of element won't suffice, nor would passing in the address of an instance of element. Won't you need to allocate many blocks within your parser?
🌐
Vaia
https://vaia.com › all textbooks › computer science › starting out with c++: from control structures through objects › chapter 9 › problem 45
Problem 45 True or False A pointer variab... [FREE SOLUTION] | Vaia
An uninitialized pointer is a pointer that has been declared but not assigned a valid memory address or set to point to a specific memory location yet. This means it could point to any random memory address, which can lead to undefined behavior ...
🌐
sqlpey
https://sqlpey.com › c › c-memory-allocation-bugs-uninitialized-pointers-memory-leaks
C Memory Allocation Bug: Fixing Uninitialized Pointers and Memory Leaks
July 22, 2025 - If malloc is used inside a function and the returned pointer is lost upon function exit (due to pass-by-value), the allocated memory becomes a leak. ANS: To fix an uninitialized pointer after a function call where memory was allocated, either have the function return the pointer to the allocated memory, or pass a pointer to the caller’s pointer variable (a double pointer) so the function can modify the caller’s pointer directly.
🌐
Cprogramming
https://cboard.cprogramming.com › c-programming › 104283-how-chk-uninitialized-pointer.html
How To Chk Uninitialized Pointer
There is nothing in the language itself that is forcing the pointer to be initialized. It is also possible to have valid code that never uses an uninitialized variable, but where you don't need to initialize the variable at the point of declaration - because that would unnecessarily write to the variable when it's not actually used.