Thursday, April 28, 2022

[FIXED] How do I get rid of the following sign-conversion warning?

Issue

I am getting the following warning whenever the function initSetArray() is called :

error: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]
  setarray = (set*)malloc(sizeof(set) * number_of_sets);   

The function initSetArray simply initializes the setarray.

void initSetArray(set *setarray, int number_of_sets, int number_of_blocks)
{
    setarray = (set*)malloc(sizeof(set) * number_of_sets);
}

I have defined two structures which are used in the helper function defined above:

typedef struct{
    uint64_t tag;   // For identifying the block
    uint8_t valid;  // Valid bit for the block
    uint8_t dirty;  // Dirty bit for the block
} block;

typedef struct{
    uint64_t index; // For identifying the set
    block* way;
} set;

I cannot exactly find out which variable is of type "long unsigned int". What can I do to resolve this issue?


Solution

In this statement

setarray = (set*)malloc(sizeof(set) * number_of_sets);

the variable number_of_sets is an integer (int), and because it is used in an expression with sizeof (size_t), the value is converted to match.

size_t is usually an unsigned long. If you don't like the warning, this would fix it:

setarray = (set*)malloc(sizeof(set) * (size_t) number_of_sets);


Answered By - Thomas Dickey
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.