I am having trouble with the following code:
#include <stdio.h>
#include <stdlib.h>
void someFunction(int number);
int main()
{
printf("Hello world!\n");
return 0;
}
void someFunction(int number)
{
char* string = (char*) malloc((number+1)*sizeof(char));
}
When I run it on my computer with the Code::Blocks IDE and the GNU GCC compiler it works without any problems. But when I use it on another machine (also with Code:Blocks and LLVM Clang Compiler compiler) I get the error
implicit conversion changes signedness: 'int' to 'unsigned long' [-Werror,-Wsign-conversion]
This error refers to the line
char* string = (char*) malloc((number+1)*sizeof(char));
If I get the error message correctly there is some "int" that is implicitly converted to "unsigned long", but I do not see where this happens.
Could you please explain this to me?
It is a warning considered by the compiler as an error due to the compiler options
-Werrorand-Wsign-conversion.Within the expression
used in the call of
mallocthe operandsizeof( char )has unsigned integer typesize_tthat is an alias for the typeunsigned long. On the other hand, the operandnumber+1has the signed typeint. The rank of the typesize_tis higher than the rank of the typeint. It means that due to the usual arithmetic conversions the operand of the typeintwill be implicitly converted to the typesize_tand thus can lose its sign.To resolve the problem just declare the function parameter like
There is no sense to pass a signed value to the function that allocates memory. And moreover the parameter of the function
mallochas the typesize_t.To make it clear then consider the following simple program.
Its output might look like
As you can see the negative variable
numberof the typeintconverted to the unsigned integer typesize_tbecomes a very big unsigned integer.