[PATCH v2] Skip the null pointer check before calling realloc

Dmitry Samersoff dmitry.samersoff at oracle.com
Wed Nov 18 13:42:57 UTC 2015


Alex,

Please notice that

> + segments = (char**)realloc( segments, (count+1)*sizeof(char*) );

would leak a memory if realloc fails (original code also has this problem).

So if jplis_assert doesn't abort entire application, it's better to write:

new_segments = (char**) realloc(segments, (count + 1) * sizeof(char*));
if (new_segments == NULL) {
   free(segments);
   goto OOM;
}

segments = new_segments;

-Dmitry

On 2015-11-18 09:24, Alex Henrie wrote:
> # HG changeset patch
> # User Alex Henrie <alexhenrie24 at gmail.com>
> # Date 1447827030 25200
> #      Tue Nov 17 23:10:30 2015 -0700
> # Node ID fb4a3c0272c0bc9c764258db65ff0b975a75b19e
> # Parent  05899a336fcd9bae4356ae1eb5cb03c55aa92c1d
> Skip the null pointer check before calling realloc.
> 
> "If ptr is a null pointer, realloc() shall be equivalent to malloc() for
> the specified size."
> http://pubs.opengroup.org/onlinepubs/9699919799/functions/realloc.html
> 
> Also, sizeof(char*) is more correct here than sizeof(char**), although
> in practice it doesn't make a difference.
> 
> diff --git a/src/java.instrument/share/native/libinstrument/InvocationAdapter.c b/src/java.instrument/share/native/libinstrument/InvocationAdapter.c
> --- a/src/java.instrument/share/native/libinstrument/InvocationAdapter.c
> +++ b/src/java.instrument/share/native/libinstrument/InvocationAdapter.c
> @@ -519,21 +519,17 @@ splitPathList(const char* str, int* path
>      int count = 0;
>      char** segments = NULL;
>      char* c = (char*) str;
>      while (*c != '\0') {
>          while (*c == ' ') c++;          /* skip leading spaces */
>          if (*c == '\0') {
>              break;
>          }
> -        if (segments == NULL) {
> -            segments = (char**)malloc( sizeof(char**) );
> -        } else {
> -            segments = (char**)realloc( segments, (count+1)*sizeof(char**) );
> -        }
> +        segments = (char**)realloc( segments, (count+1)*sizeof(char*) );
>          jplis_assert(segments != (char**)NULL);
>          segments[count++] = c;
>          c = strchr(c, ' ');
>          if (c == NULL) {
>              break;
>          }
>          *c = '\0';
>          c++;
> 


-- 
Dmitry Samersoff
Oracle Java development team, Saint Petersburg, Russia
* I would love to change the world, but they won't give me the sources.


More information about the jdk9-dev mailing list