-2

I have this piece of code:

...
#include <stdlib.h>
...

typedef struct tToken
{
    tState state;               //stav lexemu
    char *data;             //hodnota lexemu
    int row;                //radek lexemu
    int column;         //sloupec lexemu
}tToken;

tToken token;

...

void *gcMalloc(int dataSize){
    ...
    void *AllocatedData = (void*)malloc(dataSize);
    return AllocatedData;
}   

...

if(token.data == NULL)
    token.data = (char *) gcMalloc( sizeof(char) ); //there is the problem

But the error

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]

is still there... Can someone please explain me why ? And how to change it ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Michal Heneš
  • 353
  • 2
  • 4
  • 19
  • 3
    You need `#include ` to use `malloc`. (I'm assuming the warning is on the `malloc` call. If not, please update your question.) I'm sure this is a duplicate, but I'm too lazy to track it down. – Keith Thompson Oct 09 '14 at 21:27
  • Edited :) can you take a look at it ? – Michal Heneš Oct 09 '14 at 21:30
  • Where is `gcMalloc` declared? Probably you need to add a `#include` directive for whatever header declares it. (And don't cast the result of `malloc`, or of `gcMalloc` assuming it also returns `void*`. A `void*` value is implicitly converted to the target pointer type. A cast is unnecessary and can mask errors.) – Keith Thompson Oct 09 '14 at 21:32
  • 2
    [Don't cast the result of malloc (and friends)](http://stackoverflow.com/q/605845). Both casts in your snippet are at best useless, at worst they hide errors. Also, `char` is always exactly 1 `char` big. – Deduplicator Oct 09 '14 at 21:32

1 Answers1

3

My guess is that the code you posted does not accurately represent the true structure of your translation unit (or units). Apparently, in reality your gcMalloc function is either defined after you make a call to it or even defined in a different translation unit.

Meanwhile, at the point of the call

token.data = (char *) gcMalloc( sizeof(char) );

the gcMalloc function is completely unknown (not declared, not defined), which makes the compiler assume that it returns int. Hence the warning about trying to cast a 32-bit int value to a 64-bit pointer of char * type.

You have to make sure your gcMalloc function is declared before you make any attempts to call it. This is what a declaration of your gcMalloc might look like

void *gcMalloc(int dataSize);

If your program consists of multiple translation units, such declarations are typically placed in header files and included at the very top of each translation units that needs them.

And get rid of the casts. None of the casts you used in your code are necessary. It looks like you added these casts in a futile attempt to suppress diagnostic messages pointing out serious problems in your code.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765