I have a homework assignment that asks me to write a function that takes a FILE pointer named Log as one of its parameters. I have no access to the driver (just need to implement this function). When I call fprintf() to write to this Log file, I get a seg fault. When I printf the exact same thing I do not:
printf("%d\n",(bpos-pBuffer)); //Is fine--prints to standard output
fprintf(Log,"%d",(bpos-pBuffer)); //segfaults instead of writing to file.
bpos and pBuffer are both uint8_t pointer variables. The point of this is to write the value of the pointer (aka the address to which it is pointing) to the file. The correct value is reported in the printf statement.
The Log file is open and works fine when there are only two parameters to the fprtintf statement such as: fprintf(Log,"This text is written to file"); // works fine.
Edit: fprintf to stdout works as expected.
Any idea what is causing the segfault? What is the difference between fprintf and printf besides to where they are printing?
> bpos and pBuffer are both uint8_t pointer variables. The point of this is to write the value of the pointer (aka the address to which it is pointing)
You are not doing that.
> fprintf to stdout works as expected.
> The Log file is open and works fine when there are only two parameters
I would say, `undefined behaviour'. Probably is not your fault but of the client code.
However, I would like to see your full code, especially the part where you compute `bpos'
The rest of the code is irrelevant. I tested bpos and it gives the correct address. Let me amend my statement to say that the point of this is to write the value of the offset of the two pointers to the Log file.
1 2 3 4 5 6 7 8 9 10 11 12
uint8_t MyFunction(const uint8_t* pBuffer, FILE* Log)
const uint8_t* bpos=(*((uint16_t*)pBuffer)+pBuffer); //beginning of the current word
uint8_t length = *bpos; //length of the current word
//works: printf("%04x\n",(unsigned int)(bpos-pBuffer));
// works: fprintf(stdout,"%04x\n",(unsigned int)(bpos-pBuffer));
// works: fprintf(Log,"Test\nTest\nTest\n");
Fprintf return an int for the number of successfully written characters, and a negative value when there is an error.
So you should check this return value. This won't help in this case - just a concept maybe worth remembering.
Can you use sprintf to create a string - the call would be just like the printf which works. Then fprintf the string to the file. This way you can check whether the sprintf call worked first, avoid the fprintf call if it doesn't.
However the overriding thing is cire's advice.
Edit: Does it have to be C? There could be a whole different solution in C++.