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
The original code is far less likely to leak than the new, as the compiler is managing the memory for you, but if you feel must, change to:
You don’t want to dereference buffer here, any more than you did in the first bit of code. Doing so would give you the first character in the buffer, but you want the buffer’s address.