Skip to Content.
Sympa Menu

freetds - [freetds] C portability and optimization

freetds AT lists.ibiblio.org

Subject: FreeTDS Development Group

List archive

Chronological Thread  
  • From: "ZIGLIO, Frediano, VF-IT" <Frediano.Ziglio AT vodafone.com>
  • To: "FreeTDS Development Group" <freetds AT lists.ibiblio.org>
  • Subject: [freetds] C portability and optimization
  • Date: Thu, 2 Dec 2004 16:37:40 +0100

>From http://www.psgd.org/paul/docs/cport/cport08.htm

8.2.5. realloc

realloc(sto,n) takes a pointer to a region allocated with malloc and
grows or shrinks the region so that it is of size n. The return value
from realloc is a pointer to the resized storage; if the storage was
grown "in place", the return value is the same as sto. If the region was
moved, then the old contents are copied to the new storage (if n is
smaller than the old size, then only the first n units are copied). If
the region is grown, the new storage at the end is uninitialized and may
contain garbage.

Under ANSI C:

* If sto == NULL, then realloc acts like malloc.
* If n == 0, then realloc acts like free.
* If sto == NULL and n == 0, the results are undefined.

For non-ANSI versions of realloc, specifying NULL as the storage or 0 as
the new size causes undefined behavior. Thus, it is recommended that
portable programs, even those written in ANSI C, not use these features.
If it is necessary to rely on those features, use a macro or write a
function that can be configured to check for those cases explicitly.


in FreeTDS to avoid these portability problems we test pointer before
free and realloc. However I think that very few system do not support
ANSI C. So how to detect this behavior in configure.in and avoid useless
code ??

I wrote this small program

#include <stdio.h>
#include <stdlib.h>

int main()
{
void *p1, *p2;
p1 = malloc(10);
free(p1);

/* test realloc(NULL, x) act as malloc */
p2 = realloc(NULL, 10);
if (p1 != p2)
return 1;

/* test realloc(x, 0) act as free */
if (realloc(p2, 0) != NULL)
return 1;

/* now pointer should be free, test malloc return same address
*/
p2 = malloc(10);
if (p1 != p2)
return 1;

/* this should not core */
free(NULL);

return 0;
}

is it sufficient ??

freddy77



  • [freetds] C portability and optimization, ZIGLIO, Frediano, VF-IT, 12/02/2004

Archive powered by MHonArc 2.6.24.

Top of Page