Whatever value p happened to have meant that it was pointing to usable memory โ€” at least, usable enough that execution survived past the printf function calls. Who knows what you overwrote though! Answer from aioeu on reddit.com
๐ŸŒ
Reddit
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!

๐ŸŒ
Sanfoundry
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.
๐ŸŒ
Fresh2Refresh
fresh2refresh.com โ€บ home โ€บ c programming tutorial โ€บ c interview questions โ€บ what is the difference between null pointer and uninitialized pointer in c?
What is the difference between null pointer and uninitialized pointer in C?
July 5, 2018 - Null pointer is a pointer which is pointing to nothing. Null pointer points to empty location in memory. Value of null pointer is 0. We can make a pointer to point to null as below. ... Uninitialized pointers are called as wild pointers in C which points to arbitrary (random) memory location.
๐ŸŒ
HowStuffWorks
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.
๐ŸŒ
Reddit
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?
๐ŸŒ
IndiaBIX
indiabix.com โ€บ c-programming โ€บ pointers โ€บ discussion-277
Pointers Yes / No Questions - C Programming Questions and Answers Discussion Page For Q.3
... In pointers we didn't intialize the value we get the error.so we must intilaze the value.other wise we get the error. ... Unintialized pointer will be pointing to any garbage value like int* p; Initialized pointer will be pointing to a valid value in the memory like int* p = &a; where a ...
Find elsewhere
๐ŸŒ
CodeWithHarry
codewithharry.com โ€บ tutorial โ€บ c-null-pointer
NULL Pointer | C Tutorial | CodeWithHarry
That means, it points to nowhere but to a zeroth location. In contrast, an uninitialized pointer means that the pointer occupies a garbage value address. The garbage value address is still a real memory location and hence not a NULL value.
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
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.
๐ŸŒ
devRant
devrant.com โ€บ rants โ€บ 2468047 โ€บ uninitialized-pointer-is-not-the-same-as-null-pointer-uninitialized-pointer-is-n
devRant - Uninitialized pointer is not the same as NULL pointer ! Uninitialized pointer is not the same as NULL pointer ! Uninitialized pointer is not the same as NULL pointer ! Uninitialized pointer is not the same as NULL pointer !
What I meant was that global non-initialised variables in C/C++ are initialised to 0 at program start so that no explicit initialisation is required. Once execution reaches main(), this must have been done, or the runtime implementation is buggy. ... Just saw a variable in C named like this: long time_ago; //in a galaxy far away I laughed no stop.
๐ŸŒ
MITRE
cwe.mitre.org โ€บ data โ€บ definitions โ€บ 824.html
CWE - CWE-824: Access of Uninitialized Pointer (4.20)
Current News Blog Podcast News Archive CWE Board Working Groups & Special Interest Groups Email Lists
๐ŸŒ
LabEx
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.
๐ŸŒ
PrepBytes
prepbytes.com โ€บ home โ€บ c programming โ€บ wild pointers in c
Wild Pointers in C
March 30, 2023 - In C programming language, a wild pointer is an uninitialized pointer that contains a random memory address that may point to a non-existent or invalid memory location. Therefore, it is important for C programmers to always initialize pointers ...
๐ŸŒ
Vaia
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, whereas a null pointer is a pointer that is explicitly assigned the value of NULL, indicating ...