char *p; placement and mysterious segfault on sprintf(p, "%d", 3);
Tom Browder
TBrowder@cox.net
Mon May 19 21:53:00 GMT 2003
OK, here is your program with one way to fix it:
This is sprintf1.c source:
-------------------------
#include <stdio.h>
int
main()
{
int c;
int d;
char p[64]; /* <== p points to allocated local space (memory); an
alternative way is to use space (memory) from the heap through malloc*/
printf("a\n"); /* writing to a stream (file: stdout) */
sprintf(p, "%d", 3); /* writing to buffer p */
printf("b\n"); /* writing to a stream (file: stdout */
/* check p */
printf("the value of buffer p is '%s'\n", p); /* writng to stdout */
return 0;
}
If you know FORTRAN, the sprintf() function is kind of like an internal
write. All you are doing is creating a zero-terminated string out of other
data types, including possibly other strings. It MUST have a user-provided
buffer to write into--and the buffer MUST be large enough for the value to
be written (including the terminating 0).
More information about the Gcc-help
mailing list