GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 27-Aug-2004, 14:01
nkhambal nkhambal is offline
Regular Member
 
Join Date: Jul 2004
Location: CA USA
Posts: 313
nkhambal is a jewel in the roughnkhambal is a jewel in the rough

Segmentation error on executing socket code


Hi all,

On execution of following socket code with my function my_ctime(),generates segmentation fault,Without it (replacing my_ctime with ctime(&now)),it works fine.

I wrote a seperate program to test my_ctime function there is executes properly without any problem.Any suggestion where am i going wrong.

My Socket Code where I am using my_ctime() function.

CPP / C++ / C Code:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>


#define PORT 2000
FILE *logfp;
typedef char * str_t; 
str_t my_ctime();
void sigchld_handler(int s)
    {
        while(wait(NULL) > 0);
    }

int main ()
{
struct sockaddr_in my_addr,rem_addr;
char *ip="101.0.0.200";
int sockfd,inout_sockfd,size_in;
char *msg="Hi there!!!!!";
int len,bytes_sent;
int yes=1;
struct sigaction sa;

time_t	now;

my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(PORT);
my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
//inet_aton(ip,&(my_addr.sin_addr)));
memset(&(my_addr.sin_zero),'\0',8);

if ((logfp=fopen("syslog.msg","w")) == NULL)
{
	printf("\nFailed to Open syslog file...Exiting\n");
	exit(1);
}

if ((sockfd=socket(AF_INET,SOCK_STREAM,0)) == -1)
{
	perror("Socket open error");
	exit(1);
} else {
	fprintf(logfp,"\n%s: Socket Opened\n",my_ctime());
}

if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
            perror("setsockopt");
            exit(1);
        }

if ((bind(sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))) == -1)
{
	perror("Socket bind error");
	exit(1);
} else {
	fprintf(logfp,"\n%s: Socket Bind\n",my_ctime());
}

if ((listen(sockfd,10) == -1))
{
	perror("Socket listen error");
	exit(1);
} else {
	if ((strcmp("0.0.0.0",inet_ntoa(my_addr.sin_addr))) == 0)
	{
		fprintf(logfp,"%s: Listening on any available ip on port %d....\n",my_ctime(),PORT);
	} else {
	fprintf(logfp,"\n%s: Listening on ip %s port %d....\n",my_ctime(),inet_ntoa(my_addr.sin_addr),PORT);
	}
}

sa.sa_handler = sigchld_handler; // reap all dead processes
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_RESTART;
        if (sigaction(SIGCHLD, &sa, NULL) == -1) {
            perror("sigaction");
            exit(1);
        }

while (1)
{
size_in=sizeof(struct sockaddr_in);

if ((inout_sockfd=accept(sockfd,(struct sockaddr *)&rem_addr,&size_in)) == -1)
{
	perror("Socket accpet error");
}

fprintf(logfp,"%s :server: got connection from %s\n",my_ctime(),inet_ntoa(rem_addr.sin_addr));

	if (!fork())
	{
		close(sockfd);
		len=strlen(msg);
			if ((bytes_sent=send(inout_sockfd,msg,len,0)) == -1)
			{
				perror("Send Error");
				exit(1);
			}
			close(inout_sockfd);
			exit(0);
	}
	close(inout_sockfd);
}
return 0;
}

str_t my_ctime()
{
	char *s;
	int len;
	time_t t;
	strcpy(s,ctime(&t));
	len=strlen(s);
	s[len-1]='\0';
	return s;
}


The seperate program where my_ctime() works fine is as below.

CPP / C++ / C Code:
#include <stdio.h>
#include <time.h>

typedef char * str_t;
str_t my_time();
int main(int argc, char *argv[])
{
	printf("\n %s\n",my_time());
	return 0;
}

str_t my_time()
{
	
	char *s;
	int len;
	time_t t;
	strcpy(s,ctime(&t));
	len=strlen(s);
	s[len-1]='\0';
	return s;
}

Any suggestions??

Thanks,
  #2  
Old 30-Aug-2004, 05:08
LuciWiz's Avatar
LuciWiz LuciWiz is offline
Moderator
 
Join Date: Jul 2004
Location: Cluj-Napoca (Romania)
Posts: 893
LuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the rough
Quote:
The seperate program where my_ctime() works fine is as below.

CPP / C++ / C Code:
#include <stdio.h>
#include <time.h>

typedef char * str_t;
str_t my_time();
int main(int argc, char *argv[])
{
	printf("\n %s\n",my_time());
	return 0;
}

str_t my_time()
{
	
	char *s;
	int len;
	time_t t;
	strcpy(s,ctime(&t));
	len=strlen(s);
	s[len-1]='\0';
	return s;
}

I'm surprised it works .Did you try to call my_time a couple more times in your main? Does it still work?
I'm just saying this because when I used to program in C (a long time ago, I'm all for new and delete now ) I used to do this a little like this:

CPP / C++ / C Code:
str_t my_time()
{
        char *s;
	int len;
	time_t t;
/*    
        s = (char *)malloc((strlen(v) + 1) * sizeof(char));
        I don't know the length
*/
	s = (char *)malloc(100 * sizeof(char));
        if (s == NULL)
            return NULL;
        else
           strcpy(s,ctime(&t));
        
	len = strlen(s);
	s[len]='\0';
	return s;
}


I'm sorry if I'm wrong, I don't know how ctime works....
Hope this helps

Regards,
Luci
__________________
Please read these Guidelines before posting on the forum

"A person who never made a mistake never tried anything new."
Einstein
  #3  
Old 30-Aug-2004, 07:45
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,700
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by LuciWiz
CPP / C++ / C Code:
str_t my_time()
{
        char *s;
	int len;
	time_t t;
/*    
        s = (char *)malloc((strlen(v) + 1) * sizeof(char));
        I don't know the length
*/
	s = (char *)malloc(100 * sizeof(char));
        if (s == NULL)
            return NULL;
        else
           strcpy(s,ctime(&t));
        
	len = strlen(s);
	s[len]='\0';
	return s;
}




This might show the expected results, but represents a potential memory leak. It puts the responsibility on the calling program to delete the allocated memory after it is used. (Not a good thing.)

Every time this routine is called, a new amount of memory (100 bytes) is allocated. It must be un-allocated before the main program exits.

Instead of the malloc(), why not just use

CPP / C++ / C Code:
static char s[100]; /* whatever is required to hold the result of ctime() */

The "static" means that the array is allocated once (when the main program is loaded for its executation), and remains in place with whatever value is put into it by this routine. When main() finally exits, all memory associated with this program is returned to the system. This is not true of memory that was obtained from malloc() unless the program specifically deletes it.

Regards,

Dave
  #4  
Old 30-Aug-2004, 12:53
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,700
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold
Quote:
Originally Posted by davekw7x
It puts the responsibility on the calling program to delete the allocated memory after it is used. (Not a good thing.)

Dave

A clarification: I am sorry if I created any confusion by my careless use of the word "delete". Memory that is obtained by use of the standard library function malloc() must be returned to the system by a call to the standard library function free().

In C++, recommended functions are new and delete.

Dave
 
 

Recent GIDBlogMeeting the local Iraqis by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: Formatting C / C++ code WaltP C Programming Language 1 06-Jan-2008 23:59
[PROGRAM] Winsock Programming Max Payne MS Visual C++ / MFC Forum 1 08-Mar-2007 23:38

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 13:57.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.