Upon calling the sprintf function to format a string, something unexpected was printed
printf("%d;%s;%s;%d;%d;\n", ptr->programmaType, ptr->titel, ptr->zender, ptr->start, ptr->einde);
prints "0;Stargate;scifi;0;0;" while
printf("%d;", ptr->einde);
prints "42", which is the value of ptr->einde. I've also tried
printf("%d;%s;%s;%d;%d;", 0, "Stargate", "scifi", 0, 42);
which prints correctly, so I'm guessing the problem is related to the variables. Last thing I tried was
int bug = ptr->einde;
printf("%d;%s;%s;%d;%d;\n", ptr->programmaType, ptr->titel, ptr->zender, ptr->start, bug);
which also failed to print correctly... I have no idea what the hell is happening.
Note: ptr->start and ptr->einde are defined als time_t types, but seeing as printf works with a single argument I doubt that's a problem.
You said that ptr->start and ptr->einde are time_t type. This type is not not fully portable and can be any "integer or real-floating type", so it's possible that they are not being handled correctly on your system when you try to print them as int types.
Try casting it to something known and then printing:
printf("%d;%s;%s;%ld;%ld;\n", ptr->programmaType, ptr->titel,
ptr->zender, (long)ptr->start, (long)ptr->einde);
I guess your definition of ptr->einde is not of type int.
And you are using "%d" in the printf specifier which expects an int value.
Use the correct specifier for the correct type and printf behaves.
No printf is not limited in length, except in embedded implementations where it must be able to print at least 4095 chars.
time_t is probably a 64 bit integer value. The solution is to cast your variable to (uint64_t) and using PRIu64 format specifier.
printf("%d;%s;%s;%"PRIu64";%"PRIu64";\n",
ptr->programmaType,
ptr->titel, ptr->zender,
(uint64_t)ptr->start,
(uint64_t)ptr->einde);
Related
I don't understand why the result of the if statement below is always incorrect:
unsigned long is_linux;
printf("plz. enter a digit : ");
gets(str);
sscanf(str,"%d",&is_linux);
printf("the value of is_linux = %d \n",is_linux);
if(is_linux==1)
printf("Here is 1 ! \n");
else
printf("There is 0 ! \n");
I can only get "There is 0 !" statement, even if I entered "1". Furthermore, printf() statement displays the value of is_linux (1) correctly:
plz. enter a digit : 1
the value of is_linux = 1
There is 0 !
It works well if I change the variable to another name, for instance,test. Is there any reason for not using is_linux variable ? I've compiled above source code using gcc at x86_64-redhat-linux.
In your code
sscanf(str,"%d",&is_linux);
causes undefined behavior.
is_linux is of type unsigned long, it demands the conversion specifier to be lu.
Passing wrong (mismatched) type of argument to any conversion specifier causes undefined behavior.
No. You should be able to use the variable name. is_linux is not reserved and it's not a keyword. Worst-case scenario, it could (but shouldn't) be a macro (linux commonly is, unfortunately). Preemptively, or if you get compilation errors because it is a macro on your platform, you could #undef it first.
(Make sure the rest of your code is correct.)
The datatype you are assigning to is_linux is not compatible. You set it as a long, but giving it an int so when you check with your if statement you are checking for a long value, not int.
Thank you so much, there.
All comments were very helpful to me for finding root cause.
Actually, it was very simple reason, data type.
Simply, I changed %d to %lu in both of sscanf and printf and got correct answer.
My machine was 64bit lunux system and it treated unsigned long as 8-byte unit.
And also, I misunderstood %d could cover all the integer data types.
Anyway, I'm very appreciate all you guy's comments. Thank you :)
I think the title does not suit well for my question. (I appreciate it, if someone suggests an Edit)
I am learning C with "Learn C The Hard Way.". I am using printf to output values using format specifiers. This is my code snippet:
#include <stdio.h>
int main()
{
int x = 10;
float y = 4.5;
char c = 'c';
printf("x=%d\n", x);
printf("y=%f\n", y);
printf("c=%c\n", c);
return 0;
}
This works as I expect it to. I wanted to test it's behavior when it comes to conversion. So everything was ok unless I made it to break by converting char to float by this line:
printf("c=%f\n", c);
Ok, I'm compiling it and this is the output:
~$ cc ex2.c -o ex2
ex2.c: In function ‘main’:
ex2.c:13:3: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
printf("c=%f\n", c);
^
The error clearly tells me that It cannot convert from int to float, But this does not prevent the compiler from making an object file, and the confusing part is here, where I run the object file:
~$ ./ex2
x=10
y=4.500000
c=c
c=4.500000
As you can see printf prints the last float value it printed before. I tested it with other values for y and in each case it prints the value of y for c. Why this happen?
Your compiler is warning you about the undefined behaviour you have. Anything can happen. Anything from seeming to work to nasal demons. A good reference on the subject is What Every C Programmer Should Know About Undefined Behavior.
Normally, int can convert to double just fine:
int i = 10;
double d = i; //works fine
printf is a special kind of function. Since it can take any number of arguments, the types have to match exactly. When given a char, it is promoted to int when passed in. printf, however, uses the %f you gave it to get a double. That's not going to work.
Here is how one would implement their own variadic function, taken from here:
int add_nums(int count, ...)
{
int result = 0;
va_list args;
va_start(args, count);
for (int i = 0; i < count; ++i) {
result += va_arg(args, int);
}
va_end(args);
return result;
}
count is the number of arguments that follow. There is no way for the function to know this without being told. printf can deduce it from the format specifiers in the string.
The other relevant part is the loop. It will execute count times. Each time, it uses va_arg to get the next argument. Notice how it gives va_arg the type. This type is assumed. The function needs to rely on the caller to pass in something that gets promoted to int in order for the va_arg call to work properly.
In the case of printf, it has a defined list of format specifiers that each tell it which type to use. %d is int. %f is double. %c is also int because char is promoted to int, but printf then needs to represent that integer as a character when forming output.
Thus, any function that takes variadic arguments needs some caller cooperation. Another thing that could go wrong is giving printf too many format specifiers. It will blindly go and get the next argument, but there are no more arguments. Uh-oh.
If all of this isn't enough, the standard explicitly says for fprintf (which it defines printf in terms of) in C11 (N1570) §7.21.6.1/9:
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
All in all, thank your compiler for warning you when you are not cooperating with printf. It can save you from some pretty bad results.
Since printf is a varargs function, parameters cannot be converted automatically to the type expected by the function. When varargs functions are called, parameters undergo certain standard conversions, but these will not convert between different fundamental types, such as between integer and float. It's the programmer's responsibility to ensure that the type of each argument to printf is appropriate for the corresponding format specifier. Some compilers will warn about mismatches because they do extra checking for printf, but the language doesn't allow them to convert the type -- printf is just a library function, calls to it must follow the same rules as any other function.
Here is a very general description, which may be slightly different depending on the compiler in use...
When printf("...",a,b,c) is invoked:
The address of the string "..." is pushed into the stack.
The values of each of the variables a, b, c are pushed into the stack:
Integer values shorter than 4 bytes are expanded to 4 bytes when pushed into the stack.
Floating-point values shorter than 8 bytes are expanded to 8 bytes when pushed into the stack.
The Program Counter (or as some call it - Instruction Pointer) jumps to the address of function printf in memory, and execution continues from there.
For every % character in the string pointed by the first argument passed to function printf, the function loads the corresponding argument from the stack, and then - based on the type specified after the % character - computes the data to be printed.
When printf("%f",c) is invoked:
The address of the string "%f" is pushed into the stack.
The value of the variable c is expanded to 4 bytes and pushed into the stack.
The Program Counter (or as some call it - Instruction Pointer) jumps to the address of function printf in memory, and execution continues from there.
Function printf sees %f in the string pointed by the first argument, and loads 8 bytes of data from the stack. As you can probably understand, this yields "junk data" in the good scenario and a memory access violation in the bad scenario.
What is %*d ? I know that %d is used for integers, so I think %*d also must related to integer only? What is the purpose of it? What does it do?
int a=10,b=20;
printf("\n%d%d",a,b);
printf("\n%*d%*d",a,b);
Result is
10 20
1775 1775
The %*d in a printf allows you to use a variable to control the field width, along the lines of:
int wid = 4;
printf ("%*d\n", wid, 42);
which will give you:
..42
(with each of those . characters being a space). The * consumes one argument wid and the d consumes the 42.
The form you have, like:
printf ("%*d %*d\n", a, b);
is undefined behaviour as per the standard, since you should be providing four arguments after the format string, not two (and good compilers like gcc will tell you about this if you bump up the warning level). From C11 7.20.6 Formatted input/output functions:
If there are insufficient arguments for the format, the behavior is undefined.
It should be something like:
printf ("%*d %*d\n", 4, a, 4, b);
And the reason you're getting the weird output is due to that undefined behaviour. This excellent answer shows you the sort of things that can go wrong (and why) when you don't follow the rules, especially pertaining to this situation.
Now I wouldn't expect this to be a misalignment issue since you're using int for all data types but, as with all undefined behaviour, anything can happen.
When used with scanf() functions, it means that an integer is parsed, but the result is not stored anywhere.
When used with printf() functions, it means the width argument is specified by the next format argument.
The * is used as an indication that the width is passed as a parameter of printf
in "%*d", the first argument is defined as the total width of the output, the second argument is taken as normal integer.
for the below program
int x=6,p=10;
printf("%*d",x,p);
output: " 10"
the first argument ta passed for *, that defines the total width of the output... in this case, width is passed as 6. so the length of the entire output will be 5.
now to the number 10, two places are required (1 and 0, total 2). so remaining 5-2=3 empty string or '\0' or NULL character will be concatenated before the actual output
I have the following code, but I'm not sure what %0x%x means in the following code?
sprintf(buf, "pixel : %0x%x \n", gpbImageData[100]);
OutputDebugString(buf);
gpbImageData[100] is pointing to an image data in the memory.
Your example causes undefined behaviour. The format string will cause sprint to expect two int values:
%0x
%x
Both of these mean exactly the same thing - print a value as a hexadecimal number. However, the call you've shown passes only one argument.
Are you sure it doesn't say 0x%x? If it doesn't, it's probably supposed to... that would be more normal, and will print the passed-in value as a hexadecimal number prefixed with 0x.
Your code as shown should cause a warning. clang gives:
example.c:5:15: warning: more '%' conversions than data arguments [-Wformat]
printf("%0x%x\n", 125987);
~^
1 warning generated.
and gcc says:
example.c: In function ‘main’:
example.c:5: warning: too few arguments for format
example.c:5: warning: too few arguments for format
Both without providing any flags at all.
You certainly meant this format string "0x%x"
sprintf(buf, "pixel : 0x%x \n", gpbImageData[100]);
This adds the 0x prefix to the hexadecimal numbers when they are written in buf.
Note that you can achieve the same thing with the flag character #:
sprintf(buf, "pixel : %#x \n", gpbImageData[100]);
The correct format is "0x%x" as ouah and Carl Norum said. Whatever gpbImageData[100] content (pointer or number), %x will print its value as a hexadecimal number. 0x is just a text. Maybe "gpbImageData" is an array of pointers.
What's going on here:
printf("result = %d\n", 1);
printf("result = %f\n", 1);
outputs:
result = 1
result = 0.000000
If I ensure the type of these variables before trying to print them, it works fine of course. Why is the second print statement not getting implicitly converted to 1.00000?
In the second case you have a mismatch between your format string and the argument type - the result is therefore undefined behavio(u)r.
The reason the 1 is not converted to 1.0 is that printf is “just” a C function with a variable number of arguments, and only the first (required) argument has a specified type (const char *). Therefore the compiler “cannot” know that it should be converting the “extra” argument—it gets passed before printf actually reads the format string and determines that it should get a floating point number.
Now, admittedly your format string is a compile-time constant and therefore the compiler could make a special case out of printf and warn you about incorrect arguments (and, as others have mentioned, some compilers do this, at least if you ask them to). But in the general case it cannot know the specific formats used by arbitrary vararg functions, and it's also possible to construct the format string in complex ways (e.g. at runtime).
To conclude, if you wish to pass a specific type as a “variable” argument, you need to cast it.
An undefined behavior. An int is being treated as float
The short answer is that printf isn't really C++. Printf is a C function which takes a variable argument list, and applies the provided arguments to the format string basis the types specified in the format string.
If you want any sort of actual type checking, you should use streams and strings - the actual C++ alternatives to good old C-style printf.
Interesting, presumably it's fine if your put '1.0'
I suppose the printf only gets the address of the variable, it has no way of knowing what it was. But I would have thought the compiler would have the decency to warn you.