sprintf can not work in ruby c source?

H

Haoqi Haoqi

here is my simple test:
where is my mistake??

#include "ruby.h"
#include "stdio.h"
static VALUE
tests(){
char *s1="a ";
char *s2=" b";
char *buf;
sprintf(buf,"%s after %s",s1,s2);
printf(buf);
return Qnil;
}
void Init_hello(){
rb_define_global_function("tests",tests,0);
}
 
M

Maik Schmidt

Haoqi said:
here is my simple test:
where is my mistake??

#include "ruby.h"
#include "stdio.h"
static VALUE
tests(){
char *s1="a ";
char *s2=" b";
char *buf;
sprintf(buf,"%s after %s",s1,s2);
printf(buf);
return Qnil;
}
void Init_hello(){
rb_define_global_function("tests",tests,0);
}
I guess your problem is that buf is an uninitialized pointer pointing to an
arbitrary memory location. If you declare it like this
char buf[200]
your program should work.
 
H

Haoqi Haoqi

Francis said:
Um, you realize you're writing right into a random memory location? If
you're not an experienced C programmer, you may want to reconsider your
project to write a Ruby extension.
I am not an experienced C programmer,and just learn to write a Ruby
extension with c.
 
H

Haoqi Haoqi

Maik said:
Haoqi said:
sprintf(buf,"%s after %s",s1,s2);
printf(buf);
return Qnil;
}
void Init_hello(){
rb_define_global_function("tests",tests,0);
}
I guess your problem is that buf is an uninitialized pointer pointing to
an
arbitrary memory location. If you declare it like this
char buf[200]
your program should work.
Oh,Yes,Thank you very much!~

C:\ext\1>ruby client.rb
a after b
^_^
 
H

hemant

here is my simple test:
where is my mistake??

#include "ruby.h"
#include "stdio.h"
static VALUE
tests(){
char *s1="a ";
char *s2=" b";
char *buf;
sprintf(buf,"%s after %s",s1,s2);
printf(buf);
return Qnil;
}
void Init_hello(){
rb_define_global_function("tests",tests,0);
}


You have to be very careful when working with c. The code above has a
couple of classic security vulnerabilities.

Since you are not dealing with user-controlled buffers, it's not that big of
a deal, but here's a couple tips:

1) in general, don't use sprintf. use snprintf().

char * s1 = "a ";
char * s2 = "b ";
char buf[1024];
snprintf(buf,sizeof(buf),"%s after %s",s1,s2);

2) always use a string literal as the format string to functions which take
them ( printf() , snprintf() , etc... ):

printf("%s",buf);

If you're interested in what can be done if these errors are made, check out
these papers:

http://doc.bughunter.net/buffer-overflow/smash-stack.html
http://doc.bughunter.net/format-string/exploit-fs.html


Thanks for the links Adam.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,241
Messages
2,571,221
Members
47,856
Latest member
mmorais

Latest Threads

Top