I am trying to scan a bunch of characters into an array. I have used malloc to set the original size of the array, but I want to use realloc to increase the size if the user enters more characters than the initial size allows. I am not quite sure where to put the realloc, or if it should be within a conditional statement.
char *strscan(void) {
int size = sizeof(char) * 10;
char *a = malloc(size);
// Below I try to read character input from the user and store it in the array.
while (a != EOF) {
scanf("%c", a);
if (trace) printf("%c", *a);
++a;
a = realloc(a, 2 * size);
}
return a;
}
As of now I still get heap buffer overflow upon entering, for example, 15 characters.
++a;
a = realloc(a, 2 * size);
This is the problem. The first argument of realloc
must be a pointer that is returned by the malloc
family functions, or a null pointer. a
used to be one, but by ++a;
, it's not any more.