Using fscanf with dynamically allocated buffer.

Posted by ryyst on Stack Overflow See other posts from Stack Overflow or by ryyst
Published on 2010-03-27T14:32:29Z Indexed on 2010/03/27 14:43 UTC
Read the original article Hit count: 403

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about c

    Related posts about dynamic