Skip to content
Snippets Groups Projects
Commit e2e60ba1 authored by Antoine's avatar Antoine
Browse files

T1-1.

parent 4ef49485
Branches
No related merge requests found
t1*
t2*
\ No newline at end of file
......@@ -8,7 +8,7 @@ int main ()
int histogram [10];
printf("enter numnber: ");
scanf("%d", &SIZE);
int generated_numbers[SIZE];
int generated_numbers[SIZE];
for(int i=0;i<10;i++)
{
histogram[i]=0;
......
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int SIZE;
int histogram [10];
printf("enter number: ");
scanf("%d", &SIZE);
int* generated_numbers = malloc(SIZE * sizeof(SIZE));
for(int i=0;i<10;i++)
{
histogram[i]=0;
}
srand(1000);
for(int i=0;i<SIZE;i++)
{
generated_numbers[i] = rand()%10;
}
for(int i=0;i<SIZE;i++)
{
histogram[generated_numbers[i]]++;
}
for(int i=0;i<10;i++)
{
printf("Value (%d) has been found %d times\n", i, histogram[i]);
}
}
# T1-1
We can see that the program segfaults when entering a value between 10^7 and 10^19. Then, starting with 10^19 approximately, is stops segfaulting, but starts giving wrong results.
This is because we set a SIZE of 100 in the program, so the compiler will assume that SIZE will not be higher than 100 (which is wrong because the user can set more than 100 when running the program). So the operating system will allocate at least 100 integers for the "generated_numbers" array, but not necessarily more. This means that if the user choses a size of more than 100, the program will try to write after the allocated space for "generated_numbers", which may result in a segfault.
In addition to that, the SIZE is stored in an integer variable, so if the user choses a size that is higher than INT_MAX, the content of the variable SIZE will be undefined, because it cannot store the number entered by the user. This explains the wrong results after entering a value higher than INT_MAX.
To fix the issue, we first need to allocate the space for "generated_numbers" in the stack instead of the heap (which is what the program currently does). This gives us the ability to set the size of the array at run time instead of compile time. To do that, we use "malloc". We should also add a check to avoid the user to input a number that is higher than INT_MAX, but this isn't straightforward, as we cannot check if an integer is higher than INT_MAX after storing it.
(See T1-1_fixed.c)
# T1-2
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment