Concept

Uninitialized variable

Summary
In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software. A common assumption made by novice programmers is that all variables are set to a known value, such as zero, when they are declared. While this is true for many languages, it is not true for all of them, and so the potential for error is there. Languages such as C use stack space for variables, and the collection of variables allocated for a subroutine is known as a stack frame. While the computer will set aside the appropriate amount of space for the stack frame, it usually does so simply by adjusting the value of the stack pointer, and does not set the memory itself to any new state (typically out of efficiency concerns). Therefore, whatever contents of that memory at the time will appear as initial values of the variables which occupy those addresses. Here's a simple example in C: void count( void ) { int k, i; for (i = 0; i < 10; i++) { k = k + 1; } printf("%d", k); } The final value of k is undefined. The answer that it must be 10 assumes that it started at zero, which may or may not be true. Note that in the example, the variable i is initialized to zero by the first clause of the for statement. Another example can be when dealing with structs. In the code snippet below, we have a struct student which contains some variables describing the information about a student. The function register_student leaks memory contents because it fails to fully initialize the members of struct student new_student. If we take a closer look, in the beginning, age, semester and student_number are initialized. But the initialization of the first_name and last_name members are incorrect. This is because if the length of first_name and last_name character arrays are less than 16 bytes, during the strcpy, we fail to fully initialize the entire 16 bytes of memory reserved for each of these members.
About this result
This page is automatically generated and may contain information that is not correct, complete, up-to-date, or relevant to your search query. The same applies to every other page on this website. Please make sure to verify the information with EPFL's official sources.