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.
Discussions

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
How can I pass an un-initialized pointer as an argument to a function in C?
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; } More on reddit.com
🌐 r/C_Programming
19
10
February 6, 2022
How is the destination that an uninitialized pointer in c points to determined? - Stack Overflow
I know that if a pointer is declared in C (and not initialized), it will be pointing to a "random" memory address which could contain anything. How is where it actually points to determined though? More on stackoverflow.com
🌐 stackoverflow.com
April 15, 2013
Declaring a pointer without initializing
An object-oriented and type-safe ... and includes support for component-oriented programming. ... It's OK since you set the pointer before you actually make use of it. However, if possible, don't do it to prevent accidentally using it before you assign it. ... David Lowndes---so if ptr_i is not assigned with the address of i then it would become a wild pointer? ... It's uninitialized, which for ... More on learn.microsoft.com
🌐 learn.microsoft.com
2
0
September 3, 2023
🌐
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.
🌐
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.
Find elsewhere
🌐
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 ...
🌐
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.
🌐
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.
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.

🌐
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.
🌐
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 ...
🌐
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.