MaMu MaMu - 5 months ago 30
C Question

Passing arguments to function (int to size_t)

In function

I'm calling

Please see the code and the comments.

My problem is size. In
I see it is 380316. I try to pass it to writeFile.

But while stepping here I'm getting very large number(3832907636190596508).

What am I doing wrong. I'd expect, that 380316 will be passed.

int writeFile(char *name, unsigned char *buff, size_t *size,const char *dir )
FILE * pFile;
chdir (dir);
pFile = fopen ( name, "wb");
//(gdb) print *size
//$5 = 3832907636190596508
fwrite (buff , sizeof(unsigned char), *size, pFile);
fclose (pFile);

return 1;
int writeDmpFile(GTree *tree, char *filename)
char dmpfilename[32];

dmpfilename[0] ='\0';
dmpParams_t params;
params.buff[0] ='\0';
int size =0;
params.size=&size ;
g_tree_foreach(tree, (GTraverseFunc)writeDmpFileLine, &params);
sprintf (dmpfilename, "InstrumentList_FULL.csv_%.*s", 15, filename);
//here (gdb) print size
//$1 = 380316
writeFile(dmpfilename, ( unsigned char *)params.buff, ( size_t *)&size , dmpdir);//(size_t *)params.size, dmpdir);


There are two fundamental problems here.

  1. You declared size to be an int, but really it needs to be a size_t. Change its type to size_t.
  2. You should not be passing the address of size to writeFile. You should be passing it as a const value param. You don't need to modify it, nor do you. So make that clear in the signature of the function.

As a general rule, any time you encounter a type mismatch compiler error and are tempted to suppress the error with a cast, you are almost certainly making a mistake. The compiler reported an error because you made a mistake. Sure you can shut the compiler up, but experience tells me that the compiler is usually right, and we humans are very good at making mistakes.

So, don't suppress type mismatch compiler errors with casts. Seek to understand why the types don't match and thus resolve the problem.