0
The user will provide multiple (first given number) triple entries with the first number being 0, the second number being the number of disease cases at a given age (third number) or the first number being 1, the second and third numbers being the extremes of an age interval. I have to link "number of cases" with "age" and be able to edit this number of cases, have the possibility of receiving more cases for an age already cited previously (first number: 0). In addition, it will provide the numbers X and Y, so I have to print the number of cases related to the ages between X and Y (first number: 1). The language I’m using is C.
I tried that code:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int l[3], *list, n = 5;
void add(int X, int Y){
while (Y < n){
n = n * 2;
list = realloc(list, n * sizeof(int));
}
list[Y] += X;
}
void consult(int X, int Y){
int print = 0;
for (int k = X; k <= Y; ++k){
print += list[k];
}
printf("%d\n", print);
}
int main() {
int P;
scanf("%d", &P);
list = (int*)calloc(n, sizeof(int));
for (int i = 0; i < P; ++i){
for (int j = 0; j < 3; ++j){
scanf("%d", &l[j]);
}
if (l[0] == 0){
add(l[1],l[2]);
} else {
consult(l[1],l[2]);
}
}
free(list);
return 0;
}
In the example:
20
0 194 9
1 7 41
0 102 38
1 30 43
0 22 49
1 34 56
1 15 20
1 34 57
1 34 51
0 128 39
0 97 57
0 114 25
0 10 82
0 127 35
1 66 164
0 60 85
0 155 48
1 60 186
1 10 384
0 166 950
it is running correctly. However in the example:
40
0 151 25
0 5 3
0 99 1
0 109 14
0 115 15
0 110 1
0 191 2
0 94 9
1 11 13
1 25 31
1 1 33
1 14 26
0 49 31
1 28 33
1 18 34
1 16 23
1 28 38
1 13 26
1 2 5
1 17 29
0 132 8
1 21 24
0 137 0
1 0 13
1 8 26
1 12 20
0 22 63
1 5 8
1 24 70
1 51 61
1 36 40
0 164 42
1 55 70
0 134 112
0 71 105
0 101 7
0 17 67
1 56 252
0 172 363
0 18 188
is saying "maximum stack or memory size exceeded, or maybe invalid pointer (code 139)".
How can I correct that mistake?
Note: it is an obligation to start the vector with size 5 and, if the size is not sufficient, you have to double the previous memory capacity until the size is sufficient.
Note the fact that when you use the function
realloc
all bytes exceeding the previous size have indeterminate value. This is a different behavior from the functioncalloc
that Zera the allocated area.– anonimo
@anonimo But replace the function
realloc
forcalloc
hasn’t changed a bit.– Rebeca Lie Yatsuzuka Silva
I didn’t tell you to replace it. Since you do not assign an initial value to the allocated area which exceeds the previous allocation will contain memory junk, but you assume that it contains zero. Another thing is that in function
consult
you do not check if Y is within the allocated area, consider that is what may not be true.– anonimo