This is the mail archive of the mailing list for the GCC project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[PATCH] ada: use a definition for xstrdup() which returns NULL when out of memory

The current definition of xstrdup() used in the RTS in adaint.h will
generate a segmentation fault if malloc() returns NULL. This one is
a more portable definition of strdup().

It uses GCC capability to use statements in expressions but that is
not a problem as the RTS is always compiled with the newly compiled GCC.

Also, there is no need to use strcpy() because memcpy() is available and
we already know the length of the data to be copied as it has been
computed to determine how many bytes should be allocated by malloc().

Tested on x86.

2007-10-30  Samuel Tardieu  <>

	* adaint.h (xstrdup): Define xstrdup() so that it behaves as
	strdup() and returns NULL when memory could not be allocated
	by malloc() instead of generating a segmentation fault. This
	gives its user a chance to gracefully handle the error. Also,
	this version uses memcpy() instead of strcpy() because the
	length of the string to copy has already been determined
	by a previous call to strlen().
 gcc/ada/adaint.h |    6 +++++-
 1 files changed, 5 insertions(+), 1 deletions(-)

diff --git a/gcc/ada/adaint.h b/gcc/ada/adaint.h
index 131fe1f..222ac56 100644
--- a/gcc/ada/adaint.h
+++ b/gcc/ada/adaint.h
@@ -174,7 +174,11 @@ extern void   __gnat_plist_init                    (void);
 #ifdef IN_RTS
 /* Portable definition of strdup, which is not available on all systems.  */
-#define xstrdup(S)  strcpy ((char *) malloc (strlen (S) + 1), S)
+#define xstrdup(S)  ({						\
+      unsigned len = strlen (S) + 1;				\
+      char *newstr = malloc (len);				\
+      newstr ? (char *) memcpy (newstr, S, len) : newstr;	\
+    })
 /* This function returns the version of GCC being used.  Here it's GCC 3.  */

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]