Thread: Unexpected terimnation

  1. #1
    Registered User
    Join Date
    Aug 2011
    Posts
    385

    Unexpected terimnation

    why does this program terminate unexpedly when the control reaches line no.33

    Code:
    #include<stdio.h>
    #include<string.h>
     
    void swap(char *, char *); 
    void sort(int (*)(const char *, const char *), void(*)(char *,char *), char*[]);
     
    int main()
    {
        char *names[] = {"rakesh", "rakshas" , "Kalantari" , "phisaddi"}; int i;
     
        void swap(char *,char *);
     
        sort(strcmp, swap, names);
    
    	for(i=0;i<4;i++)
    		printf("\n%s",names[i]);
    }
     
    void sort(int (*strcmp)(const char *, const char *), void (*swap)(char *,char *), char **name)
    {
    	int i,j;
    
    	for(i=1;i<=3;i++)
    		for(j=1;j<=4-i;j++)
    			if(strcmp(name[j-1],name[j])>0)
    				swap(name[j-1],name[j]);
    }
    
    void swap(char *s, char *t)
    {
    	char temp[10];
    	strcpy(temp,t);
    	strcpy(t,s);
    	strcpy(s,temp);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The problem is that the pointers point to the first character of string literals. As such, modifying what the pointers point to results in undefined behaviour.

    If you want to swap the strings, you have to swap the pointers, not use strcpy to write to what the pointers point to.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unexpected output
    By juice in forum C Programming
    Replies: 24
    Last Post: 11-18-2011, 11:18 PM
  2. unexpected output
    By crash88 in forum C Programming
    Replies: 2
    Last Post: 05-16-2006, 09:03 PM
  3. Unexpected Error
    By Vendicate in forum Linux Programming
    Replies: 7
    Last Post: 04-04-2006, 12:01 PM
  4. Unexpected results
    By Syked4 in forum C Programming
    Replies: 2
    Last Post: 06-07-2005, 09:41 PM
  5. Unexpected behaviour
    By fnoyan in forum C++ Programming
    Replies: 5
    Last Post: 03-05-2005, 09:45 AM