fgets() question

R

Roman Mashak

Hello, All!

Is there a common rule to allocate memory for buffer for using in
fgets() ? For example:

fgets(buf, SIZE, stdin);

Is it mandatory to call malloc() before using fgets() ?

With best regards, Roman Mashak. E-mail: (e-mail address removed)
 
G

Gordon Burditt

Is there a common rule to allocate memory for buffer for using in
fgets() ? For example:

fgets(buf, SIZE, stdin);

Is it mandatory to call malloc() before using fgets() ?

No. You could, for example, declare:
char buf[SIZE];
which does not require malloc().

Gordon L. Burditt
 
C

CBFalconer

Roman said:
Is there a common rule to allocate memory for buffer for using in
fgets() ? For example:

fgets(buf, SIZE, stdin);

Is it mandatory to call malloc() before using fgets() ?

No. However it is mandatory to have buf refer to allocated memory
of at least SIZE bytes.
 
M

Malcolm

Roman Mashak said:
Is there a common rule to allocate memory for buffer for using in
fgets() ? For example:

fgets(buf, SIZE, stdin);

Is it mandatory to call malloc() before using fgets() ?
char *buf;

buf = malloc(SIZE);
if(buf)
fgets(buf, SIZE, stdin);

/* when finished with buf */
free(buf);

or

char buf[SIZE];

fgets(buf, SIZE, stdin);

are both OK.

The second is more common, because there's not usually much point calling
malloc() when you know the amount of memory you need at compile time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top