Error msg - Segmentation fault

P

Pedro Pinto

Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {


I don't know why but if i write

if(!strcmp(argv[1],"-s") == 0) {

no error occurs.....

can someone explain to me what is the error?
I've done a printf before the if and the result is 0, or true if you
prefer.

i start the client with

client -s localhost 17500

Thanks in advance for any help!

Regards

Pedro Pinto

Here is the code:




-------------------------------------------CLIENTE.C


#include "cliente.h"






/* Função Main*/

int main (int argc, char *argv[]) {




/* função que apresenta sintaxe do programa*/

void syntax() {



printf("Sintaxe do programa cliente:\n");

printf(" cliente -s <endereço_servidor>
<porto_servidor>\n");

printf(" -endereço_servidor: (opcional) IP do
servidor\n");

printf(" -porto_servidor: porto do servidor\n");

}





int sock;

int broadcast = 1;

struct sockaddr_in server;

struct sockaddr_in cli;

int endereco_servidor;

int porto_servidor;



/* criacao da socket */

if ((sock = socket(AF_INET,SOCK_DGRAM,0)) <0) {

perror("socket");

exit(1);

}

else {

printf("\nCliente: socket criada \n");

}


if(strcmp(argv[1],"-s") == 0) {
printf("\nentrei n o verifica ip, estamos a funcionar com endereco ip
inserido");

endereco_servidor = inet_aton(atoi(argv[2]), &server.sin_addr);
porto_servidor = atoi(argv[3]);



}

else {//enviar em broadcast

printf("Não foi fornecido o endereço IP, a enviar em broadcast");

porto_servidor = atoi(argv[1]);
server.sin_addr.s_addr = htonl(INADDR_BROADCAST);


/* activar broadcast na socket */

if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&broadcast,
sizeof (int)) <0) {

perror("setsockopt");

exit(1);

}

}


void checkPort(porto_servidor) {



if(porto_servidor < 17500 || porto_servidor > 17599) {

printf("Cliente: O porto tem de ser entre 17500 e 17599!\n");

exit(-1);

}

}






/* limpa a estrutura */

bzero((char *)&server, sizeof(server));



/* definir a família de protocolo e porto */

server.sin_family = AF_INET;

server.sin_port = htons(porto_servidor);





/* limpa a estrutura */

bzero((char *)&cli, sizeof(cli));





/* inicio da comunicação com o servidor*/

printf("\nEstou antes da criacao de msg");

int msg[] = {0,1,2,3,4};
printf("\nsizeof msg = $d", sizeof(msg));

int buffer[BUFFSIZE];



/* limpar o buffer */

memset(buffer, 0, BUFFSIZE);



/* enviar a mensagem para o servidor*/

if(sendto(sock, msg, 5, 0, (struct sockaddr *)&server,
sizeof(server)) <0) {

perror("sendto");

exit(1);

}

else {

printf("Cliente: Mensagem enviada com sucesso");

//printMessage(buffer);

}



/* timeout de 10 segundos */

struct timeval timeout;

fd_set readfds;

int sel;

char buf1[64];



/* limpar a fd_set */

FD_ZERO(&readfds);



/* colocar o file descriptor no fd_set */

FD_SET(sock, &readfds);



while(1){

timeout.tv_sec = 10; //segundos

timeout.tv_usec = 0; //microsegundos



sel = select(sock+1, &readfds, NULL, NULL, &timeout);

if (sel == -1) {

perror("select");

}

else if (sel == 0) {

printf("Ocorreu um timeout! Não foi recebida nenhuma mensagem em
10s.\n");

}

else { // foi retornado um file descriptor



if (FD_ISSET(sock, &readfds)) {

recv(sock, buf1, sizeof(buf1), 0);

}

}

}

/* ler a resposta do servidor */

if(recvfrom(sock, buffer, BUFFSIZE, 0, NULL, NULL) < 0) {

perror("rcvfrom");

exit(1);

}

else {

printf("Cliente: Mensagem recebida com sucesso");

//printMessage(buffer);
}







/* fecho da socket */

close(sock);


}


----------------------------------------------------

CLIENTE.H --------------------------


#ifndef CLIENTE

#define CLIENTE

#define BUFFSIZE 6804



/* Bibliotecas necessarias */

#include <sys/socket.h>

#include <sys/types.h>

#include <stdio.h>

#include <errno.h>

#include <sys/time.h>

#include <stdlib.h>

#include <arpa/inet.h>

#include <netinet/in.h>

#include <netdb.h>
#include <string.h>





/* Ficheiros necessarios */

//#include "cli_aux.c"

//#include "cli_imp.c"



/* Definicao das funcoes */

/*******************************************

* Apresenta a sintaxe do programa cliente *

*******************************************/

void syntax();



/**************************************************************************

* Verifica se o numero de parametros do programa cliente estao
correctos *

* argc: numero de argumentos
*


**************************************************************************/

void checkParameters(int argc);



/*********************************************************

* Verifica se a porta esta entre os valores pretendidos *

* port: porta do servidor *

*********************************************************/

void checkPort(int port);



/********

* MAIN *

********/

int main(int argc, char* argv[]);



#endif
 
S

Spiros Bousbouras

Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {


I don't know why but if i write

if(!strcmp(argv[1],"-s") == 0) {

no error occurs.....

can someone explain to me what is the error?
I've done a printf before the if and the result is 0, or true if you
prefer.

i start the client with

client -s localhost 17500

Thanks in advance for any help!

Regards

Pedro Pinto

Here is the code:




-------------------------------------------CLIENTE.C


#include "cliente.h"






/* Função Main*/

int main (int argc, char *argv[]) {




/* função que apresenta sintaxe do programa*/

void syntax() {

I don't know what this syntax means and I doubt
it is standard C. Turn this into standard C and I
may be able to help. Of course sockets are not part
of standard C either but it may be that your problem
is not sockets specific.

<REST OF CODE SNIPPED>
 
I

Ian Collins

Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {
You don't appear to be checking argc to see if there is an argv[1].

I'd also avoid nested functions, which are not standard C.
 
P

Pedro Pinto

Ian Collins escreveu:
Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {
You don't appear to be checking argc to see if there is an argv[1].

I'd also avoid nested functions, which are not standard C.

Hi there........

I cannot believe it but the error was with the printf..................

if i move the \n to the end of the string to be putted on the monitor
it works well.........

I still cannot believe it and i would love to know why does this
happen...

Regards

Pedro
 
K

Keith Thompson

Spiros Bousbouras said:
Pedro Pinto wrote: [...]
int main (int argc, char *argv[]) {

/* função que apresenta sintaxe do programa*/

void syntax() {

I don't know what this syntax means and I doubt
it is standard C. Turn this into standard C and I
may be able to help. Of course sockets are not part
of standard C either but it may be that your problem
is not sockets specific.

It looks like a nested function definition. It's not supported in
standard C, but some compilers may support it as an extension.

OP: Whatever compiler you're using should have an option or set of
options to disable extensions.
 
S

Spiros Bousbouras

Ian said:
Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {
You don't appear to be checking argc to see if there is an argv[1].

But he said he calls the programme with
client -s localhost 17500
So there is a argv[1].
 
I

Ian Collins

Spiros said:
Ian Collins wrote:

Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {

You don't appear to be checking argc to see if there is an argv[1].


But he said he calls the programme with
client -s localhost 17500
So there is a argv[1].
But he should still check.
 
S

Spiros Bousbouras

Keith said:
Spiros Bousbouras said:
Pedro Pinto wrote: [...]
int main (int argc, char *argv[]) {

/* função que apresenta sintaxe do programa*/

void syntax() {

I don't know what this syntax means and I doubt
it is standard C. Turn this into standard C and I
may be able to help. Of course sockets are not part
of standard C either but it may be that your problem
is not sockets specific.

It looks like a nested function definition.

I assumed that much but it still doesn't make it
clear what the semantics are with his compiler so
we don't know if he uses it in the way it's supposed
to be used.
 
S

Spiros Bousbouras

Pedro said:
Ian Collins escreveu:
Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {
You don't appear to be checking argc to see if there is an argv[1].

I'd also avoid nested functions, which are not standard C.

Hi there........

I cannot believe it but the error was with the printf..................

I doubt it.
if i move the \n to the end of the string to be putted on the monitor
it works well.........

Perhaps it works well but the problem is almost certainly
somewhere else.
I still cannot believe it and i would love to know why does this
happen...

Well , that makes two of us.

By the way is there some reason you're printing all
those dots ? Does your '.' key get stuck ? Even if it
does you can still use backspace to erase the excess
dots.
 
R

Richard Tobin

I still cannot believe it and i would love to know why does this
happen...

Have you tried running it under a debugger to see exactly where the
error occurs?

-- Richard
 
R

Richard

Pedro Pinto said:
Ian Collins escreveu:
Pedro said:
Hello there.

I've created a socket program so exchange some messages with a server.

The problem is the following:

it compiles well but when running it gives a segmentation error here:
if(strcmp(argv[1],"-s") == 0) {
You don't appear to be checking argc to see if there is an argv[1].

I'd also avoid nested functions, which are not standard C.

Hi there........

I cannot believe it but the error was with the printf..................

if i move the \n to the end of the string to be putted on the monitor
it works well.........

I still cannot believe it and i would love to know why does this
happen...

Littering code with printfs is frowned upon by many. It can insert bugs
: especially in C where a stray "++" in a printf() and so forth can easily escape the
eye.

I would suggest using a debugger wherever possible.

http://heather.cs.ucdavis.edu/~matloff/Debug/Debug.pdf

eplains better than I can the reasons for using them. Don't believe the
crap about real programmers not needing them because they designed their
programs properly. All code has bugs and debuggers are there to help you
locate them. Only the most arrogant of programmers really believe they
KNOW the value of all variables in a function without having a debugger
watch confirm it.

They are also excellent for examining a core after a crash in OSs like
Linux.

In this case the inclusion of "!" might just be altering the potentially
illegal value of argv[1]. You must always check such parameters. This is
addressed by Ian's reply.
Regards

Pedro

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,739
Latest member
Clint8040

Latest Threads

Top