Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Is it legal to pass a null pointer as the first argument to realloc? Why would you want to?

Legal null pass pointer
0
Posted

Is it legal to pass a null pointer as the first argument to realloc? Why would you want to?

0

ANSI C sanctions this usage (and the related realloc(…, 0), which frees), although several earlier implementations do not support it, so it may not be fully portable. Passing an initially-null pointer to realloc can make it easier to write a self-starting incremental allocation algorithm. Here is an example–this function reads an arbitrarily-long line into dynamically-allocated memory, reallocating the input buffer as necessary. (The caller must free the returned pointer when it is no longer needed.) #include #include /* read a line from fp into malloc’ed memory */ /* returns NULL on EOF or error */ /* (use feof or ferror to distinguish) */ char *agetline(FILE *fp) { char *retbuf = NULL; size_t nchmax = 0; register int c; size_t nchread = 0; char *newbuf; while((c = getc(fp)) != EOF) { if(nchread >= nchmax) { nchmax += 20; if(nchread >= nchmax) { /* in case nchmax overflowed */ free(retbuf); return NULL; } #ifdef SAFEREALLOC newbuf = realloc(retbuf, nchmax + 1);

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.