This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Re: char *p; placement and mysterious segfault on sprintf(p, "%d", 3);


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).



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]