Thread: Program to reverse a string--segmentation fault!

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    2

    Program to reverse a string--segmentation fault!

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    int
    main(void)
    {
      char* original = (char*) malloc(80 * sizeof(char));
      char reverse[80];
      char temp[80]; //same as char* temp
      char *ptr;
    
    
      printf("Input: ");
      fgets(original, 80, stdin);
      ptr = strtok(original, " ");
    
    
      while(strtok(original, " \n") != NULL) //until end of line
      {
        ptr = strtok(NULL, " \n");
        sprintf("%s", ptr, reverse); //THIS CAUSES THE ERROR
        strcpy(reverse, temp);
      }//while
    
    
      printf("%s", reverse);
    
    
      free(original);
      
      return 0;
    }//int main(void)
    I am trying to write this program to reverse a string. If I were to give it the string "birds and bees," it would give me bees and birds in response. This program does not work, though, and results in a segmentation fault. What is my error and how do I fix it?

    Thank you.
    Last edited by echo1525; 11-10-2012 at 10:07 PM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > sprintf("%s", ptr, reverse); //THIS CAUSES THE ERROR
    sprintf(3): formatted output conversion - Linux man page
    Considering that the first parameter is supposed to be the string to WRITE into, what can you expect when you pass "%s"?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    Code:
    char temp[80]; //same as char* temp
    No, that's not true. Pointers and arrays are not the same. Read Question 6.2 of the C-FAQ.

    Bye, Andreas

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String segmentation fault
    By dojha00 in forum C Programming
    Replies: 7
    Last Post: 08-29-2012, 03:30 AM
  2. Too long string causes segmentation fault
    By heinz55 in forum C Programming
    Replies: 11
    Last Post: 08-07-2012, 06:07 PM
  3. Segmentation fault when changing a string
    By lilydjwg in forum C Programming
    Replies: 6
    Last Post: 12-02-2009, 07:43 AM
  4. segmentation fault when processing a string
    By Nakel in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2003, 04:02 PM
  5. segmentation fault when processing a string
    By EMC2 in forum C++ Programming
    Replies: 0
    Last Post: 04-24-2003, 02:56 PM