Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Is it legal to pass a null pointer as the first argument to realloc? Why would you want to?
Is it legal to pass a null pointer as the first argument to realloc? Why would you want to?
✍: Guest
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 <stdio.h>
#include <stdlib.h>
/* 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);
#else
if(retbuf == NULL) /* in case pre-ANSI realloc */
newbuf = malloc(nchmax + 1);
else newbuf = realloc(retbuf, nchmax + 1);
#endif
/* +1 for \0 */
if(newbuf == NULL) {
free(retbuf);
return NULL;
}
retbuf = newbuf;
}
if(c == '\n')
break;
retbuf[nchread++] = c;
}
if(retbuf != NULL) {
retbuf[nchread] = '\0';
newbuf = realloc(retbuf, nchread + 1);
if(newbuf != NULL)
retbuf = newbuf;
}
return retbuf;
}
(In production code, a line like nchmax += 20 can prove troublesome, as the function may do lots of reallocating. Many programmers favor multiplicative reallocation, e.g. nchmax *= 2, although it obviously isn't quite as self-starting, and can run into problems if it has to allocate a huge array but memory is limited.)
2016-03-16, 1090👍, 0💬
Popular Posts:
How do I use forms? The basic syntax for a form is: <FORM ACTION="[URL]">...&l t;/FORM>Wh...
How To Retrieve Input Values for Checkboxes Properly? - PHP Script Tips - Processing Web Forms If mu...
How can you implement MVC pattern in ASP.NET? The main purpose using MVC pattern is to decouple the ...
How To Decrement Dates by 1? - MySQL FAQs - Introduction to SQL Date and Time Handling If you have a...
How do I force the Dispose method to be called automatically, as clients can forget to call Dispose ...