Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. why segmentation fault !

why segmentation fault !

Scheduled Pinned Locked Moved C / C++ / MFC
11 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • W wbgxx

    I want to swap two string

    #include <stdio.h>
    #include <string.h>
    void swap(char *a1, char *a2)
    {
    char ch[20];
    if (a1 != NULL || a2 != NULL)
    {
    strcpy(ch, a1);
    strcpy(a1, a2);
    strcpy(a2, ch);

    	}
    else
    	return ;
    

    }

    int main()
    {
    char *a1 = "hello";
    char *a2 = "world";
    printf("Before the swap a1=%s, a2=%s", a1, a2);
    swap(a1, a2);
    printf("After the swap a1=%s, a2=%s", a1, a2);
    return 0;
    }

    A Offline
    A Offline
    Aescleal
    wrote on last edited by
    #2

    Remember what I said about the difference between pointers and arrays earlier? What's probably happening is that the arrays your pointers are pointing to are in a chunk of memory in the program's text section. This section is usually read only - you don't want programs modifying their own code as a rule. The first strcpy will work okay - you're copying data from the text section to an array on the stack, which is read/write. when you do the second strcpy you're copying from the text section to another bit of the text section and BOOM says the operating system. If you declare a1 and a2 as:

    char a1[] = "hello";
    char a2[] = "world";

    it'll start working if I'm correct. Another way of looking at it is...

    char a[] = "Hello";

    translates to: - allocate enough memory on the stack to hold 6 characters - copy "Hello\0" into the memory while:

    char *a = "Hello";

    translates to: - allocate enough memory on the stack to hold a pointer - initialise the pointer with the address of the constant string "Hello" in the text section Incidentally this being able to use a char * to point at a const block of characters initialised at compile time is a legacy of the original K&R C which didn't have things like const - it's one of the irritating bits of programming in C. Unfortunately you just have to get used to it. Hope that helps, Ash

    W 1 Reply Last reply
    0
    • W wbgxx

      I want to swap two string

      #include <stdio.h>
      #include <string.h>
      void swap(char *a1, char *a2)
      {
      char ch[20];
      if (a1 != NULL || a2 != NULL)
      {
      strcpy(ch, a1);
      strcpy(a1, a2);
      strcpy(a2, ch);

      	}
      else
      	return ;
      

      }

      int main()
      {
      char *a1 = "hello";
      char *a2 = "world";
      printf("Before the swap a1=%s, a2=%s", a1, a2);
      swap(a1, a2);
      printf("After the swap a1=%s, a2=%s", a1, a2);
      return 0;
      }

      F Offline
      F Offline
      Fareed Rizkalla
      wrote on last edited by
      #3

      Use & with the * in swap. char*& a1

      1 Reply Last reply
      0
      • A Aescleal

        Remember what I said about the difference between pointers and arrays earlier? What's probably happening is that the arrays your pointers are pointing to are in a chunk of memory in the program's text section. This section is usually read only - you don't want programs modifying their own code as a rule. The first strcpy will work okay - you're copying data from the text section to an array on the stack, which is read/write. when you do the second strcpy you're copying from the text section to another bit of the text section and BOOM says the operating system. If you declare a1 and a2 as:

        char a1[] = "hello";
        char a2[] = "world";

        it'll start working if I'm correct. Another way of looking at it is...

        char a[] = "Hello";

        translates to: - allocate enough memory on the stack to hold 6 characters - copy "Hello\0" into the memory while:

        char *a = "Hello";

        translates to: - allocate enough memory on the stack to hold a pointer - initialise the pointer with the address of the constant string "Hello" in the text section Incidentally this being able to use a char * to point at a const block of characters initialised at compile time is a legacy of the original K&R C which didn't have things like const - it's one of the irritating bits of programming in C. Unfortunately you just have to get used to it. Hope that helps, Ash

        W Offline
        W Offline
        wbgxx
        wrote on last edited by
        #4

        thanks ! but I still have question why this can be run

        #include <iostream.h>
        #include <cstring>
        void swap(char *,char *);
        int main()
        {char str1[20]="hello",str2[20]="how are you ";
        char pt[20];
        cout<<"str1"<<" "<<str1<<endl;
        cout<<"str2"<<" "<<str2<<endl;
        strcpy(pt,str1);
        strcpy(str1,str2);
        strcpy(str2,pt);
        cout<<"str1"<<" "<<str1<<endl;
        cout<<"str2"<<" "<<str2<<endl;
        return 0;
        }

        A D 2 Replies Last reply
        0
        • W wbgxx

          I want to swap two string

          #include <stdio.h>
          #include <string.h>
          void swap(char *a1, char *a2)
          {
          char ch[20];
          if (a1 != NULL || a2 != NULL)
          {
          strcpy(ch, a1);
          strcpy(a1, a2);
          strcpy(a2, ch);

          	}
          else
          	return ;
          

          }

          int main()
          {
          char *a1 = "hello";
          char *a2 = "world";
          printf("Before the swap a1=%s, a2=%s", a1, a2);
          swap(a1, a2);
          printf("After the swap a1=%s, a2=%s", a1, a2);
          return 0;
          }

          L Offline
          L Offline
          Lost User
          wrote on last edited by
          #5

          Your problem seems to be obvious.You are not allowed to modify string contents if they are allocated like a1 and a2.You should probably change your code like that:

          char a1\[20\];
          strcpy(a1,"Hello");	
          
          char a2\[20\];
          strcpy(a2,"world");
          

          In addition there was almost the same thread recently.

          Life is a stage and we are all actors!

          W A 2 Replies Last reply
          0
          • L Lost User

            Your problem seems to be obvious.You are not allowed to modify string contents if they are allocated like a1 and a2.You should probably change your code like that:

            char a1\[20\];
            strcpy(a1,"Hello");	
            
            char a2\[20\];
            strcpy(a2,"world");
            

            In addition there was almost the same thread recently.

            Life is a stage and we are all actors!

            W Offline
            W Offline
            wbgxx
            wrote on last edited by
            #6

            wonderful! I see, thanks in advance!

            1 Reply Last reply
            0
            • W wbgxx

              thanks ! but I still have question why this can be run

              #include <iostream.h>
              #include <cstring>
              void swap(char *,char *);
              int main()
              {char str1[20]="hello",str2[20]="how are you ";
              char pt[20];
              cout<<"str1"<<" "<<str1<<endl;
              cout<<"str2"<<" "<<str2<<endl;
              strcpy(pt,str1);
              strcpy(str1,str2);
              strcpy(str2,pt);
              cout<<"str1"<<" "<<str1<<endl;
              cout<<"str2"<<" "<<str2<<endl;
              return 0;
              }

              A Offline
              A Offline
              Aescleal
              wrote on last edited by
              #7

              That works because you're using arrays - you're saying "allocate 20 bytes on the stack and initialise it with this string." With the original version you were saying "Initialise this pointer to point at a chunk of read only memory." The difference is where the data your swapping is in memory. Have a look at the address of your variables in a debugger. You'll probably see all three having similar addresses in the second version. In the first version the a1 and a2 will have similar addresses and a lot different to that of the swap temporary. Cheers, Ash

              1 Reply Last reply
              0
              • W wbgxx

                I want to swap two string

                #include <stdio.h>
                #include <string.h>
                void swap(char *a1, char *a2)
                {
                char ch[20];
                if (a1 != NULL || a2 != NULL)
                {
                strcpy(ch, a1);
                strcpy(a1, a2);
                strcpy(a2, ch);

                	}
                else
                	return ;
                

                }

                int main()
                {
                char *a1 = "hello";
                char *a2 = "world";
                printf("Before the swap a1=%s, a2=%s", a1, a2);
                swap(a1, a2);
                printf("After the swap a1=%s, a2=%s", a1, a2);
                return 0;
                }

                N Offline
                N Offline
                Niklas L
                wrote on last edited by
                #8

                There is another access violation waiting to happen in your swap function. None of the arguments in a call to strcpy can be null. You need to check for a1 != NULL && a2 != NULL. Also, watch out for the buffer overruns you might encounter if a1 is longer than 19 characters, or the allocated buffers of a2 and a1 are of different sizes.

                home

                1 Reply Last reply
                0
                • L Lost User

                  Your problem seems to be obvious.You are not allowed to modify string contents if they are allocated like a1 and a2.You should probably change your code like that:

                  char a1\[20\];
                  strcpy(a1,"Hello");	
                  
                  char a2\[20\];
                  strcpy(a2,"world");
                  

                  In addition there was almost the same thread recently.

                  Life is a stage and we are all actors!

                  A Offline
                  A Offline
                  Aescleal
                  wrote on last edited by
                  #9

                  You don't need the explicit strcpy call, the compiler will generate the code to initialise the array properly if you just use:

                  char a[ 20 ] = "Hello";

                  Ash

                  1 Reply Last reply
                  0
                  • W wbgxx

                    thanks ! but I still have question why this can be run

                    #include <iostream.h>
                    #include <cstring>
                    void swap(char *,char *);
                    int main()
                    {char str1[20]="hello",str2[20]="how are you ";
                    char pt[20];
                    cout<<"str1"<<" "<<str1<<endl;
                    cout<<"str2"<<" "<<str2<<endl;
                    strcpy(pt,str1);
                    strcpy(str1,str2);
                    strcpy(str2,pt);
                    cout<<"str1"<<" "<<str1<<endl;
                    cout<<"str2"<<" "<<str2<<endl;
                    return 0;
                    }

                    D Offline
                    D Offline
                    David Crow
                    wrote on last edited by
                    #10

                    Read here.

                    "One man's wage rise is another man's price increase." - Harold Wilson

                    "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                    "Man who follows car will be exhausted." - Confucius

                    A 1 Reply Last reply
                    0
                    • D David Crow

                      Read here.

                      "One man's wage rise is another man's price increase." - Harold Wilson

                      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

                      "Man who follows car will be exhausted." - Confucius

                      A Offline
                      A Offline
                      Aescleal
                      wrote on last edited by
                      #11

                      Thanks for posting that, the piccies work far better than my text. Ash

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups