Using fscanf with dynamically allocated buffer.
- by ryyst
Hi,
I got the following code:
char buffer[2047];
int charsRead;
do {
if(fscanf(file, "%2047[^\n]%n%*c", buffer, &charsRead) == 1) {
// Do something
}
} while (charsRead == 2047);
I wanted to convert this code to use dynamically allocated variables so that when calling this code often I won't get heavy memory leakage. Thus, I tried this:
char *buffer = malloc(sizeof(char) * 2047);
int *charsRead = malloc(sizeof(int));
do {
if(fscanf(file, "%2047[^\n]%n%*c", *buffer, charsRead) == 1) {
// Do something
}
} while (*charsRead == 2047);
Unfortunately, this does not work. I always get “EXC_BAD_ACCESS” errors, just before the if-statement with the fscanf call.
What am I doing wrong?
Thanks for any help!
-- Ry