Line 1:
int temp2 [4];
for(j=0;j<=4;j++){
for(i=0;i<=4;i++) {
temp2[j] = temp2[j] + election[i][j];
}
}
printf("%d",temp2[3]);
In this above example, the nested for loops sums up the columns of a 5x5 table.
However, the last column is always summed up incorrectly.
When I changed Line 1 to:
int temp2[4] = {0};
All of a sudden the calculations came out perfectly! What exactly happened between the initialization of the array?
If an array is uninitialized, does that mean its last element will always contain some garbage value?
If an array is uninitialized, does that mean its last element will always contain some garbage value?
Whether they contain a garbage value or any value at all is a matter of interpretation, because any attempt to read from such uninitialized variables is undefined behaviour (UB)1. So, you can't even check what is stored in those variables. In practice, UB may manifest itself as "garbage" values being printed out, but technically anything could happen.
Also note that you are accessing the array out of bounds. That is also UB.
for(j=0;j<=4;j++){ /* Oops! Should be j < 4 */
[1] This is a simplification. In practice, implementations can assign unspecified values to uninitialized variables, or use trap representations. This means the results or reading an uninitialized variables could simply be unspecified. But they could also do whatever a given implementation does when a trap value is read. I find it easier to lump everything under UB. See related question: What happens to a declared, uninitialized variable in C? Does it have a value?
Yes, an uninitialized array will contain unpredictable garbage. You must initialize it.
If an array is uninitialized, does that mean its last element will always contain some garbage value?
If the array is not global or static, yes it will contain the garbage value. The BSS initializes the static or globalvariable or memory location to default values unless the variable is initially assigned some value.
Thus, the information at the memory location is overwritten by compiler the program may crash.
Now, when you are accessing that memory what you get is undefined behavior.
Also, note that the snippet is accessing the array out of bounds. So, please use:
int temp2 [4];
for(j=0;j<=3;j++){
for(i=0;i<=3;i++) {
or
int temp2 [4];
for(j=0;j<4;j++){
for(i=0;i<4;i++) {
First, As Jonathan Leffler mentioned, You are looping too much - You initialized an array of 4 but looping 5 times. Try changing your outer loop to j<4 and inner loop to i<4:
Line 1: int temp2 [4];
for(j=0;j<4;j++){
for(i=0;i<4;i++) {
temp2[j] += election[i][j];
}
}
printf("%d",temp2[3]);
You should also initialize your array, as you can't predict what is in memory at the point of creation (also depends on what language you're using)
An uninitialized array will contain garbage data. I've notice that in the last version of visual studio if the array is of simple data types such as int than the compiler/ide automatically initialize it to zeros, but I wouldn't rely on it. As a rule, I recommend you initialize your arrays before you start doing operations like summing etc.
Related
I was reading through some source code and found a functionality that basically allows you to use an array as a linked list? The code works as follows:
#include <stdio.h>
int
main (void)
{
int *s;
for (int i = 0; i < 10; i++)
{
s[i] = i;
}
for (int i = 0; i < 10; i++)
{
printf ("%d\n", s[i]);
}
return 0;
}
I understand that s points to the beginning of an array in this case, but the size of the array was never defined. Why does this work and what are the limitations of it? Memory corruption, etc.
Why does this work
It does not, it appears to work (which is actually bad luck).
and what are the limitations of it? Memory corruption, etc.
Undefined behavior.
Keep in mind: In your program whatever memory location you try to use, it must be defined. Either you have to make use of compile-time allocation (scalar variable definitions, for example), or, for pointer types, you need to either make them point to some valid memory (address of a previously defined variable) or, allocate memory at run-time (using allocator functions). Using any arbitrary memory location, which is indeterminate, is invalid and will cause UB.
I understand that s points to the beginning of an array in this case
No the pointer has automatic storage duration and was not initialized
int *s;
So it has an indeterminate value and points nowhere.
but the size of the array was never defined
There is neither array declared or defined in the program.
Why does this work and what are the limitations of it?
It works by chance. That is it produced the expected result when you run it. But actually the program has undefined behavior.
As I have pointed out first on the comments, what you are doing does not work, it seems to work, but it is in fact undefined behaviour.
In computer programming, undefined behavior (UB) is the result of
executing a program whose behavior is prescribed to be unpredictable,
in the language specification to which the computer code adheres.
Hence, it might "work" sometimes, and sometimes not. Consequently, one should never rely on such behaviour.
If it would be that easy to allocate a dynamic array in C what would one use malloc?! Try it out with a bigger value than 10 to increase the likelihood of leading to a segmentation fault.
Look into the SO Thread to see the how to properly allocation and array in C.
I know that declaring a char[] variable in a while loop is scoped, having seen this post: Redeclaring variables in C.
Going through a tutorial on creating a simple web server in C, I'm finding that I have to manually clear memory assigned to responseData in the example below, otherwise the contents of index.html are just continuously appended to the response and the response contains duplicated contents from index.html:
while (1)
{
int clientSocket = accept(serverSocket, NULL, NULL);
char httpResponse[8000] = "HTTP/1.1 200 OK\r\n\n";
FILE *htmlData = fopen("index.html", "r");
char line[100];
char responseData[8000];
while(fgets(line, 100, htmlData) != 0)
{
strcat(responseData, line);
}
strcat(httpResponse, responseData);
send(clientSocket, httpResponse, sizeof(httpResponse), 0);
close(clientSocket);
}
Correct by:
while (1)
{
...
char responseData[8000];
memset(responseData, 0, strlen(responseData));
...
}
Coming from JavaScript, this was surprising. Why would I want to declare a variable and have access to the memory contents of a variable declared in a different scope with the same name? Why wouldn't C just reset that memory behind the scenes?
Also... Why is it that variables of the same name declared in different scopes get assigned the same memory addresses?
According to this question: Variable declared interchangebly has the same pattern of memory address that ISN'T the case. However, I'm finding that this is occurring pretty reliably.
Not completely correct. You don't need to clear the whole responseData array - clearing its first byte is just enough:
responseData[0] = 0;
As Gabriel Pellegrino notes in the comment, a more idiomatic expression is
responseData[0] = '\0';
It explicitly defines a character via its code point of zero value, while the former uses an int constant zero. In both cases the right-side argument has type int which is implicitly converted (truncated) to char type for assignment. (Paragraph fixed thx to the pmg's comment.)
You could know that from the strcat documentation: the function appends its second argument string to the first one. If you need the very first chunk to get stored into the buffer, you want to append it to an empty string, so you need to ensure the string in the buffer is empty. That is, it consists of the terminating NUL character only. memset-ting the whole array is an overkill, hence a waste of time.
Additionally, using a strlen on the array is asking for troubles. You can't know what the actual contents of the memory block allocated for the array is. If it was not used yet or was overwritten with some other data since your last use, it may contain no NUL character. Then strlen will run out of the array causing Undefined Behavior. And even if it returns successfuly, it will give you the string's length bigger than the size of the array. As a result memset will run out of the array, possibly overwriting some vital data!
Use sizeof whenever you memset an array!
memset(responseData, 0, sizeof(responseData));
EDIT
In the above I tried to explain how to fix the issue with your code, but I didn't answer your questions. Here they are:
Why do variables (...) in different scopes get assigned the same memory addresses?
In regard of execution each iteration of the while(1) { ... } loop indeed creates a new scope. However, each scope terminates before the new one is created, so the compiler reserves appropriate block of memory on the stack and the loop re-uses it in every iteration. That also simplifies a compiled code: every iteration is executed by exactly the same code, which simply jumps at the end to the beginning. All instructions within the loop that access local variables use exactly the same addressing (relative to the stack) in each iteration. So, each variable in the next iteration has precisely the same location in memory as in all previous iterations.
I'm finding that I have to manually clear memory
Yes, automatic variables, allocated on the stack, are not initialized in C by default. We always need to explicitly assign an initial value before we use it – otherwise the value is undefined and may be incorrect (for example, a floating-point variable can appear not-a-number, a character array may appear not terminated, an enum variable may have a value out of the enum's definition, a pointer variable may not point at a valid, accessible location, etc.).
otherwise the contents (...) are just continuously appended
This one was answered above.
Coming from JavaScript, this was surprising
Yes, JavaScript apparently creates new variables at the new scope, hence each time you get a brand new array – and it is empty. In C you just get the same area of a previously allocated memory for an automatic variable, and it's your responsibility to initialize it.
Additionally, consider two consecutive loops:
void test()
{
int i;
for (i=0; i<5; i++) {
char buf1[10];
sprintf(buf1, "%d", i);
}
for (i=0; i<1; i++) {
char buf2[10];
printf("%s\n", buf2);
}
}
The first one prints a single-digit, character representation of five numbers into the character array, overwriting it each time - hence the last value of buf1[] (as a string) is "4".
What output do you expect from the second loop? Generally speaking, we can't know what buf2[] will contain, and printf-ing it causes UB. However we may suppose the same set of variables (namely a single 10-items character array) from both disjoint scopes will get allocated the same way in the same part of a stack. If this is the case, we'll get a digit 4 as an output from a (formally uninitialized) array.
This result depends on the compiler construction and should be considered a coincidence. Do not rely on it as this is UB!
Why wouldn't C just reset that memory behind the scenes?
Because it's not told to. The language was created to compile to effective, compact code. It does as little 'behind the scenes' as possible. Among others things it does not do is not initializing automatic variables unless it's told to. Which means you need to add an explicit initializer to a local variable declaration or add an initializing instruction (e.g. an assignment) before the first use. (This does not apply to global, module-scope variables; those are initialized to zeros by default.)
In higher-level languages some or all variables are initialized on creation, but not in C. That's its feature and we must live with it – or just not use this language.
With this line:
char responseData[8000];
You are saying to your compiler: Hey big C, give me a 8000 bytes chunk and name it responseData.
In runtime, if you don't specify, no one will ever clean or give you a "brand-new" chunk of memory. That means that the 8000 bytes chunk you get in every single execution can hold all the possible permutations of bits in this 8000 bytes. Something extraordinary that can happens, is that you're getting in every execution the same memory region and thus, the same bits in this 8000 bytes your big C gave to you in the first time. So, if you don't clean, you have the impression that you're using the same variable, but you're not! You're just using the same (never cleaned) memory region.
I'd add that it's part of the programmer's responsibilities to clean, if you need to, the memory you're allocating, in dynamic or static way.
Why would I want to declare a variable and have access to the memory contents of a variable declared in a different scope with the same name? Why wouldn't C just reset that memory behind the scenes?
Objects with auto storage duration (i.e., block-scope variables) are not automatically initialized - their initial contents are indeterminate. Remember that C is a product of the early 1970s, and errs on the side of runtime speed over convenience. The C philosophy is that the programmer is in the best position to know whether something should be initialized to a known value or not, and is smart enough to do it themselves if needed.
While you're logically creating and destroying a new instance of responseData on each loop iteration, it turns out the same memory location is being reused each time through. We like to think that space is allocated for each block-scope object as we enter the block and released as we leave it, but in practice that's (usually) not the case - space for all block-scope objects within a function is allocated on function entry, and released on function exit1.
Different objects in different scopes may map to the same memory behind the scenes. Consider something like
void bletch( void )
{
if ( some_condition )
{
int foo = some_function();
printf( "%d\n", foo );
}
else
{
int bar = some_other_function();
printf( "%d\n", bar );
}
It's impossible for both foo and bar to exist at the same time, so there's no reason to allocate separate space for both - the compiler will (usually) allocate space for one int object at function entry, and that space gets used for either foo or bar depending on which branch is taken.
So, what happens with responseData is that space for one 8000-character array is allocated on function entry, and that same space gets used for each iteration of the loop. That's why you need to clear it out on each iteration, either with a memset call or with an initializer like
char responseData[8000] = {0};
As M.M points out in a comment, this isn't true for variable-length arrays (and potentially other variably modified types) - space for those is set aside as needed, although where that space is taken from isn't specified by the language definition. For all other types, though, the usual practice is to allocate all necessary space on function entry.
When I try to print all the values in the array(which should be zero?), it starts printing 0's but at the end prints wonky numbers:
"(printing zeros)...0,0,0,0,0,0,0,1810432,0,1809600,0,1809600,0,0,0,5,0,3907584..."
When I extend the array, only at the end do the numbers start to mess up. Is this a memory limitation or something? Very confused, would greatly appreciate if anyone could help a newbie out.
Done in CS50IDE, not sure if that changes anything
int main()
{
int counter [100000];
for(int i = 0; i < 100000; i++)
{
printf("%i,", counter[i]);
}
}
Your array isn't initialized. You simply declare it but never actually set it. In C (and C++, Objective-C) you need to manually set a starting value. Unlike Python, Java, JavaScript or C# this isn't done for you...
which should be zero?
The above assertion is incorrect.
auto variables (variables declared within a block without the static keyword) are not initialized to any particular value when they are created; their value is indeterminate. You can't rely on that value being 0 or anything else.
static variables (declared at file scope or with the static keyword) are initialized to 0 or NULL, depending on type.
You can initialize all of the elements of the array to 0 by doing
int counter [100000] = {{0}};
If there are fewer elements in the initializer than there are elements in the array, then the extra elements are initialized as though they were static - 0 or NULL. So the first element is being explicitly initialized to 0, and the remaining 99999 elements are implicitly initialized to 0.
The reason why this is happening is because you reserved 100000*4 = 400000 bytes of memory but didn't write anything to it (didn't initialize it).
So therefore, garbage is printed if you access a memory location which hasn't been written to yet. The reason why 0's aren't printed is because we want optimization and don't want the compiler wasting time in writing to 100000 integer addresses and also the best practices expect a developer to never access a memory place that he has never written to or allocated yet. If you try printing:
printf("%d\n", counter[100000]);
This would also print a garbage value, but you didn't allocate that did you? It's because C/C++ don't restrict or raise errors when you try to do such operation unlike Java.
Try it yourself
for (int i=0; i<100000; i++) {
counter[i] = i;
printf("%d\n", counter[i]);
}
Now only numbers from 1,2,3....99999 will be printed on the screen.
When you declare an array in C, it does not set the elements to zero by default. Instead, it will be filled with whatever data last occupied that location in memory, which could be anything.
The fact that the first portion of the array contained zeros is just a coincidence.
This beginning state of an array is referred to as an "uninitialized" array, as you have not provided any initial values for the array. Before you can use the array, it should be "initialized", meaning that you specify a default value for each position.
This question already has answers here:
Array index out of bound behavior
(10 answers)
Closed 7 years ago.
Suppose I declare the following
typedef struct{
int age;
int weight;
} Man;
Then I make an array of Man such as
Man *manArr = malloc(sizeof(Man) * 2);
My understanding is that I now have two cells each capable of holding a Man type in them..but how am I able to do this then?
manArr[45] = (Man) {33, 23};
I would have imagined that I would have seg faulted because there only exists two cells but I can printf the values of manArr[45]. What's a good way to for example go through struct arrays, do something to their fields, and move on to the next without "going out of bounds" per say?
Thanks
Accessing out-of-bounds is not guaranteed to segfault. It is defined by the C standard as undefined behavior, i.e. anything can happen, including seemingly error-free behavior.
What's a good way to for example go through struct arrays, do something to their fields, and move on to the next without "going out of bounds" per say?
Remember the size of the array.
const size_t manArrSize = 2;
Man *manArr = malloc(sizeof(Man) * manArrSize);
for (size_t index = 0; index < manArrSize; ++index)
{
// Access `manArr[index]`.
}
Going out of bounds of an array causes undefined behaviour. This means that anything could happen. If you're lucky you'll get a segfault, but you may also get cases where the memory location happens to be somewhere you can access.
As for move on to the next without "going out of bounds":
You could either use an extra variable to store the size of the array, or decide on a sentinel value in the array (and allocate one more slot for it) so that if a certain element is equal to the sentinel value, you know it is the end. For example, argv uses NULL as the sentinel value.
I am starting to learn c and cannot find a clear example of handling memory violations. Currently I have written a piece of code that uses a variable and an array.
I assign a value to the variable and then populate the array with a set of initial values. However one of the values in the array is being saved at the same address as the variable and hence overwriting the variable.
Could some one please give me a simple example of how to handle such errors or to avoid such errors....thanks
Once an error such as a memory violation has occurred in C, you cannot 'handle' it. So, you have to avoid it in the first place. The way to do what you want is as follows:
int a[10];
int i;
for( i = 0; i < 10; i++ )
a[i] = 5;
This is a guess but seems pretty much your problem.
You are overwriting beyond the bounds of the array.
C does not guard you against writing beyond the bounds of an allocated array. You as a programmer must ensure you do not do so. Failing to do so will result in Undefined Behavior and then anything can happen(literally) your program might work or might not or show unusual behavior.
For eg:
int arr[10];
Declares an array of 10 integers and the valid subscript range is from 0 to 9,
You should ensure your program uses valid subscripts.