[pacman-dev] [PATCH] ensure realloc has a positive size

Allan McRae allan at archlinux.org
Tue Nov 3 11:50:37 UTC 2015


On 02/11/15 11:41, Andrew Gregory wrote:
> If given size 0 POSIX allows realloc to return a pointer that is not
> suitable for use.
> 

>From malloc(3):

"if size is equal to zero, and ptr is not  NULL,  then  the  call  is
equivalent to free(ptr)."

Is that not generally guaranteed?  Or is qsort the issue here?

> Signed-off-by: Andrew Gregory <andrew.gregory.8 at gmail.com>
> ---
>  lib/libalpm/be_local.c | 10 +++++++---
>  lib/libalpm/be_sync.c  | 10 +++++++---
>  2 files changed, 14 insertions(+), 6 deletions(-)
> 
> diff --git a/lib/libalpm/be_local.c b/lib/libalpm/be_local.c
> index 556157d..e35fc0e 100644
> --- a/lib/libalpm/be_local.c
> +++ b/lib/libalpm/be_local.c
> @@ -810,9 +810,13 @@ static int local_db_read(alpm_pkg_t *info, alpm_dbinfrq_t inforeq)
>  					files_count++;
>  				}
>  				/* attempt to hand back any memory we don't need */
> -				files = realloc(files, sizeof(alpm_file_t) * files_count);
> -				/* make sure the list is sorted */
> -				qsort(files, files_count, sizeof(alpm_file_t), _alpm_files_cmp);
> +				if(files_count > 0) {
> +					files = realloc(files, sizeof(alpm_file_t) * files_count);
> +					/* make sure the list is sorted */
> +					qsort(files, files_count, sizeof(alpm_file_t), _alpm_files_cmp);
> +				} else {
> +					FREE(files);
> +				}
>  				info->files.count = files_count;
>  				info->files.files = files;
>  			} else if(strcmp(line, "%BACKUP%") == 0) {
> diff --git a/lib/libalpm/be_sync.c b/lib/libalpm/be_sync.c
> index 25c8cbe..b09b060 100644
> --- a/lib/libalpm/be_sync.c
> +++ b/lib/libalpm/be_sync.c
> @@ -721,9 +721,13 @@ static int sync_db_read(alpm_db_t *db, struct archive *archive,
>  					files_count++;
>  				}
>  				/* attempt to hand back any memory we don't need */
> -				files = realloc(files, sizeof(alpm_file_t) * files_count);
> -				/* make sure the list is sorted */
> -				qsort(files, files_count, sizeof(alpm_file_t), _alpm_files_cmp);
> +				if(files_count > 0) {
> +					files = realloc(files, sizeof(alpm_file_t) * files_count);
> +					/* make sure the list is sorted */
> +					qsort(files, files_count, sizeof(alpm_file_t), _alpm_files_cmp);
> +				} else {
> +					FREE(files);
> +				}
>  				pkg->files.count = files_count;
>  				pkg->files.files = files;
>  			}
> 


More information about the pacman-dev mailing list