Another newbie question! "Segmentation Fault on char *"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fantasticamir
    New Member
    • Apr 2007
    • 42

    Another newbie question! "Segmentation Fault on char *"

    Guys,

    DO you know why I got segmentation fault on this piece of code?

    Code:
      char p[]={68,69,98,112,105};
      char *p1;
      for (int i=0; i<5; i++)       p1[i]=p[i];
      p1[5]='\0';
    
      cout << p1<<endl;
    Thanks,

    Amir.
    Last edited by Ganon11; Apr 16 '07, 11:45 AM. Reason: code tags added
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by fantasticamir
    Guys,

    DO you know why I got segmentation fault on this piece of code?

    char p[]={68,69,98,112, 105};
    char *p1;
    for (int i=0; i<5; i++) p1[i]=p[i];
    p1[5]='\0';

    cout << p1<<endl;

    Thanks,

    Amir.
    It is probably because "p1" does not have a size declared. Try declaring it like "char p1[5]" or "char p1[6]" if you want the nul zero character.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by ilikepython
      It is probably because "p1" does not have a size declared. Try declaring it like "char p1[5]" or "char p1[6]" if you want the nul zero character.
      Variable p1 cannot have a size declared: it's a pointer. The error is that p1 doesn't
      point to anything so storing a char at where p1 points to is shooting yourself
      in the foot or worse.

      The solution is to make p1 point to a bunch of chars, enough to hold all the
      characters that were stored in the p array.

      kind regards,

      Jos

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Mainly, youir problem comesbecause you have declared a char pointer p1, but you did not give it anything to point to. You can either make it a native chara array like ilikepython suggested, or use

        Code:
        char *p1 = new char[5]; // or the appropriate malloc() call in C

        Comment

        Working...