I have found a piece of code online that purposely has errors in the code as part of a debugging exercise. I have gotten the simple errors fixed, but there is one line which I'm not sure whether it is valid.
#include <stdlib.h>
#include <stdio.h>
struct foo {
int size;
int *array;
};
typedef struct foo bar;
bar* readArray(){
bar *fbar = (bar *)malloc(sizeof(bar));
fbar->array = (int *)malloc(sizeof(int)*2); //ADDED THIS LINE FOR TESTING
int i = 0;
int temp;
while(scanf("%d", &temp) == 1){
*(fbar->array + (i-1)) = temp; //THIS LINE HERE
i++;
}
if(i == 0){
printf("No numbers were entered!");
}
fbar->size = i;
return fbar;
}
int main(){
bar *p = readArray();
return 0;
}
I tried running it which of course causes a segfault because the example didn't malloc space for *array. I tried testing the line by mallocing space for 2 int's to test if the first 2 loops worked. I assumed the program would get a segfault after the first 2 int's are read, which did not occur (the program keeps running). Now I don't understand what that line of code does and why I am not segfaulting.
I can't exactly figure out what is the error, or if there even is an error besides the lack of malloc() for int *array.