The following program is hitting a segmentation fault, and I cannot figure out what the problem is.
#include<stdio.h>
#include<stdarg.h>
void writeformat(FILE*,char*, ...);
int main(void)
{
  FILE *fp;
  fp=fopen("file1.txt","w");
  writeformat(fp,"/modules.php?name=Top&querylang=%20WHERE%201=2%20ALL%20SELECT%201,pwd,1,1%20FROM%20nuke_authors/*");
  fclose(fp);
  return(0);
}
void writeformat(FILE *stream,char *format, ...)
{
  va_list args;
  va_start(args,format);
  vfprintf(stream,format,args);
  va_end(args);
}
I tried in gdb, and it tells me the problem is in vfprintf():
(gdb) run
Starting program: /ws/anaganes-sjc/junk 
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x2aaaaaaab000
Program received signal SIGSEGV, Segmentation fault.
0x0000003c44c7fb30 in wcslen () from /lib64/libc.so.6
(gdb) bt
#0  0x0000003c44c7fb30 in wcslen () from /lib64/libc.so.6
#1  0x0000003c44c80b27 in wcsrtombs () from /lib64/libc.so.6
#2  0x0000003c44c464b2 in vfprintf () from /lib64/libc.so.6
#3  0x0000000000400649 in writeformat (stream=0x601010, format=0x400758 "/modules.php?name=Top&querylang=%20WHERE%201=2%20ALL%20SELECT%201,pwd,1,1%20FROM%20nuke_authors/*") at junk.c:20
#4  0x0000000000400556 in main () at junk.c:9
Can you please help me find the problem?
Your format string contains escaped space characters. The escape is done with percent signs, HTML style:
"querylang=%20WHERE%201=2%20ALL%20SELECT%201..."
These percent signs have a meaning in printf style format strings. You must either render the spaces verbatim:
"querylang= WHERE 1=2 ALL SELECT 1..."
or use printf's  own escape for printing percent signs, namely %%:
"querylang=%%20WHERE%%201=2%%20ALL%%20SELECT%%201..."
or, as alk points out in a comment, use the string format and print your string as argument:
writeformat(fp, "%s", "/modules.php?name=");
which is the best way to print strings that have or could have formatting specifiers verbatim.
You get a segmentation violation, because each format specified with % except %% expects an additional argument. For example %20A withh print a binary representation of a float of width 20. It therefore expects a double argument, but you haven't specified any arguments, so vprintf tries to acess memory beyond the bound of the variable argument list.
Many compilers can warn you about format mismatches for the well-known printf functions. Some compilers allow you to label arguments of your own functions as printf like format strings. Microsoft's SAL or gcc-style attributes will let you do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With