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]

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


I use gcc (GCC) 3.2.3, but with 2.95.4 and 3.2.3 20030407 (Debian 
prerelease) the results where exactly the same.

My gcc always came from the gcc package in Debian sid distribution.

This is sprintf1.c source:
-------------------------
#include <stdio.h>

int main()
{
  int c;
  int d;
  char *p;

  printf("a\n");
  sprintf(p, "%d", 3);
  printf("b\n");

  return 0;
}

-------------------------

I compile it gcc sprintf1.c -o sprintf1. it complies without any 
errors or warnings. When I run it ./sprintf1 it produces:

a
Segmentation fault

However, when we remove either int c; or int d; or both it runs 
correctly without a segfault.

Even more wired: when we move the declaration char *p; to be before 
int d; or before int c; it also runs correctly without a segfault.
When we insert a third unused variable, for example int e; it also 
runs correctly. It only sefaults when there are exactly two variables 
declared before char *p;
These variable don'thave to be unused or be int for the program to 
segfault.

The program produces a core file when it segfaults. I have put the 
source code of the program, the executable and the core file in 
http://www.miernik.ctnet.pl/c/

What am I missing here?
Or did I found a bug in gcc?

-- 
    Miernik         ________________________ jabber:miernik@jabber.gda.pl
__ ICQ: 4004001 ___/__ tel: +48608233394 __/      mailto:miernik@ctnet.pl
Sing a declaration against US invasion in Iraq:
http://www.moveon.org/declaration/


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