This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Re: char *p; placement and mysterious segfault on sprintf(p, "%d", 3);
- From: "Tom Browder" <TBrowder at cox dot net>
- To: "Miernik" <miernik at ctnet dot pl>,<gcc-help at gcc dot gnu dot org>
- Date: Mon, 19 May 2003 16:53:20 -0500
- Subject: Re: Re: char *p; placement and mysterious segfault on sprintf(p, "%d", 3);
- References: <20030518090033.A10.4.NOFFLE@tarnica.miernik.lo>
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).