elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Arreglado, de nuevo, el registro del warzone (wargame) de EHN


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Segmentation fault
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Segmentation fault  (Leído 2,854 veces)
albdav

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Segmentation fault
« en: 11 Julio 2017, 00:12 am »

Hola estoy haciendo un codigo para una computadora linux que se comunique por el puerto rs485, el codigo funcionaba bien , pero ahora me marca error justo despues de intentar configurar el puerto. El código es el siguiente :

Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>             /* File Control Definitions           */
  4.  
  5. #include <termios.h>      /* POSIX Terminal Control Definitions */
  6.  
  7. #include <unistd.h>         /* UNIX Standard Definitions            */
  8.  
  9. #include <errno.h>           /* ERROR Number Definitions           */
  10.  
  11. #include <sys/ioctl.h>   /* ioctl() */
  12.  
  13. #include <unistd.h> //para funcion sleep()  ...delay
  14. #include <string.h>
  15.  
  16. int main()
  17. {
  18.  
  19. int fd;/*File Descriptor*/
  20.  
  21.  
  22.  
  23.  
  24. /*------------------------------- Opening the Serial Port -------------------------------*/
  25.  
  26. /* Change /dev/ttyS0 to the one corresponding to your system */
  27.  
  28. fd = open("/dev/ttyS0",O_RDWR | O_NOCTTY);           /* ttyS0 corresponde al puerto serial rs485 de UNO-1252G   */  
  29.  
  30.                                                               /* O_RDWR   - Read/Write access to serial port       */
  31.  
  32.                                                              /* O_NOCTTY - No terminal will control the process   */
  33.  
  34.                                                              /* Open in blocking mode,read will wait              */
  35.  
  36.  
  37. if(fd == -1)                                                                                           /* Error Checking */
  38. printf("\n  Error! in Opening ttyS0  ");
  39. else
  40. printf("\n  ttyS0 Opened Successfully ");
  41.  
  42.  
  43.  
  44.  
  45. /*---------- Setting the Attributes of the serial port using termios structure --------- */
  46.  
  47.  
  48. struct termios SerialPortSettings; /* Create the structure                          */
  49.  
  50. tcgetattr(fd, &SerialPortSettings); /* Get the current attributes of the Serial port */
  51.  
  52. /* Setting the Baud rate */
  53. cfsetispeed(&SerialPortSettings,B9600); /* Set Read  Speed as 9600                       */
  54. cfsetospeed(&SerialPortSettings,B9600); /* Set Write Speed as 9600                       */
  55.  
  56. /* 8N1 Mode */
  57. SerialPortSettings.c_cflag &= ~PARENB;   /* Disables the Parity Enable bit(PARENB),So No Parity   */
  58. SerialPortSettings.c_cflag &= ~CSTOPB;   /* CSTOPB = 2 Stop bits,here it is cleared so 1 Stop bit */
  59. SerialPortSettings.c_cflag &= ~CSIZE; /* Clears the mask for setting the data size             */
  60. SerialPortSettings.c_cflag |=  CS8;      /* Set the data bits = 8                                 */
  61.  
  62. SerialPortSettings.c_cflag &= ~CRTSCTS;       /* No Hardware flow Control                         */
  63. SerialPortSettings.c_cflag |= CREAD | CLOCAL; /* Enable receiver,Ignore Modem Control lines       */
  64.  
  65.  
  66. SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);          /* Disable XON/XOFF flow control both i/p and o/p */
  67. SerialPortSettings.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG);  /* Non Cannonical mode                            */
  68.  
  69. SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/
  70.  
  71. /* Setting Time outs */
  72. SerialPortSettings.c_cc[VMIN] =  10; /* Read at least 10 character */
  73. SerialPortSettings.c_cc[VTIME] = 0;  /* Wait indefinetly   */
  74.  
  75.  
  76.  
  77. if((tcsetattr(fd,TCSANOW,&SerialPortSettings)) != 0) /* Set the attributes to the termios structure*/
  78.    printf("\n  ERROR ! in Setting attributes");
  79. else
  80.                     printf("\n  BaudRate = 9600 \n  StopBits = 1 \n  Parity   = none");
  81.  
  82.  
  83.  
  84.  
  85. int RTS_flag,DTR_flag;
  86.  
  87. RTS_flag = TIOCM_RTS; /* Modem Constant for RTS pin */
  88.  
  89.        DTR_flag = TIOCM_DTR; /* Modem Constant for DTR pin */
  90.  
  91.  
  92. ioctl(fd,TIOCMBIS,&RTS_flag);/* ~RTS = 0,So ~RE pin of MAX485 is LOW,Receive Mode enabled   */
  93.  
  94.        ioctl(fd,TIOCMBIS,&DTR_flag);/* ~DTR = 0,So  DE pin of MAX485 is LOW,                       */
  95.  
  96. /////////apartir de aqui va el programa//////////////////////////////////
  97.  
  98. char *read_buffer;   /* Buffer to store the data received              */
  99.       int  bytes_read = 0;    /* Number of bytes read by the read() system call */
  100.        int i =0;
  101. char com [10];
  102. char fin [2];
  103. strcpy (com,"mosquitto_pub -h iot.eclipse.org -t testkd -m 'recibo por rs485:");
  104. strcpy (read_buffer,"no_lei_nada");
  105. strcpy (fin," '");
  106. int n= 1;
  107. int f = 1;
  108. sleep(2);
  109. tcflush(fd, TCIFLUSH);   /* Discards old data in the rx buffer            */
  110. char cmx[5];
  111.  
  112.  
  113. int  bytes_written  = 0;   /* Value for storing the number of bytes written to the port */
  114.        char *temp;          
  115.  
  116. /*------------------------------- Read data from serial port -----------------------------*/
  117. //Este es el bucle que se va a repetir para estar recibiendo constantemente información
  118.  
  119.  
  120.  
  121. // se debe de verificar si linux permite que se ejecute indefinidamente el programa, o hay que ejecutar periodicamente el mismo
  122.  
  123. while (1)
  124. {
  125. if(f<=6)
  126. {
  127.  
  128. sprintf(temp,"%d",f);
  129. strcpy(cmx, "$AA"); //comando para leer un canal del MX
  130. strcat(cmx, temp);
  131. f++;
  132. }else{
  133. sprintf(temp,"%d",n);
  134. strcpy(cmx, "cont:"); //comando para leer un canal del MX
  135. strcat(cmx, temp);
  136. }
  137. printf("\n  Me ejecuto antes de escribir f= %i , n=%i , solicitud: %s  $$$ \n", f, n, cmx);
  138. bytes_written = write(fd,cmx,sizeof(cmx));
  139. /* use write() to send data to port                                            */
  140.    /* "fd"                   - file descriptor pointing to the opened serial port */
  141.    /* "write_buffer"         - address of the buffer containing data           */
  142.    /* "sizeof(write_buffer)" - No of bytes to write                               */
  143. printf("\n   Solicitud: %s ", cmx);
  144. //printf("\n  %d Bytes written to ttyUSB0", bytes_written);
  145. //printf("\n +----------------------------------+\n\n");
  146. //sleep(2);
  147. //tcflush(fd, TCIFLUSH);   /* Discards old data in the rx buffer            */
  148.  
  149. while (bytes_read==0)
  150. bytes_read = read(fd,&read_buffer,32); /* Read the data                   */
  151.  
  152.  
  153.                //printf("\n\n  Bytes Rxed -%d", bytes_read); /* Print the number of bytes read */
  154.  
  155.                printf("\n Recibo:   ");
  156.  
  157. for(i=0;i<bytes_read;i++)              /*printing only the received characters*/
  158. printf("%c",read_buffer[i]);
  159.  
  160. printf("\n +----------------------------------+\n\n");
  161. strcat(com, read_buffer);
  162. strcat(com, fin);
  163. printf("\n  %s  \n",com);
  164.  
  165. system(com);
  166. system("clear");
  167. printf("reinicio de lectura %i, %i", f, n);
  168. //reinicio de variables
  169. bytes_read=0;
  170. strcpy (com,"mosquitto_pub -h iot.eclipse.org -t testkd -m 'recibo por rs485:");
  171. read_buffer =  '\0';
  172. tcflush(fd, TCIFLUSH);
  173.  
  174. if (n==32)
  175. {
  176. n=1;
  177. f=1;
  178. sleep(1.5); //aqui se ingresa el tiempo de espera en segundos en el que despues de una solicitud de
  179. //todos los controladores de la estación se vuelve a solicitar info a todos--------en este caso 1.5 seg
  180. }
  181. else if (f>6)
  182. {
  183. n++;
  184. sleep(1.5); //aqui se ingresa el tiempo de espera en segundos entre la solicitud a un controlador
  185. //para que cada minuto se solicite 1 vez la info de cada disp se divide 60s / 38 disp = 1.57
  186.  
  187. }
  188.  
  189.  
  190. }
  191.  
  192.        close(fd); /* Close the serial port */
  193. }
  194.  
Me da el siguiente error:

Segmentation fault (core dumped)


· Los códigos deben ir en etiquetas GeSHi
>aquí las reglas del foro
-Engel Lex


« Última modificación: 11 Julio 2017, 02:30 am por engel lex » En línea

engel lex
Moderador Global
***
Desconectado Desconectado

Mensajes: 15.514



Ver Perfil
Re: Segmentation fault
« Respuesta #1 en: 11 Julio 2017, 02:30 am »

te recomiendo usar el debugger de tu ide para conseguirlo... este error probablemente es un array fuera de rango o una variable desbordada


En línea

El problema con la sociedad actualmente radica en que todos creen que tienen el derecho de tener una opinión, y que esa opinión sea validada por todos, cuando lo correcto es que todos tengan derecho a una opinión, siempre y cuando esa opinión pueda ser ignorada, cuestionada, e incluso ser sujeta a burla, particularmente cuando no tiene sentido alguno.
MAFUS


Desconectado Desconectado

Mensajes: 1.603



Ver Perfil
Re: Segmentation fault
« Respuesta #2 en: 11 Julio 2017, 15:23 pm »

Por ejemplo, fíjate en el array com: es de 10 elementos, eso es para una cadena de 9 caracteres efectivos y, sin embargo, con strcpy le introduces una cadena muy larga.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Ayuda con segmentation fault
Programación C/C++
puppetz 7 3,114 Último mensaje 26 Junio 2014, 23:58 pm
por Eternal Idol
segmentation fault en mi programa
Programación C/C++
:Luigi 3 4,703 Último mensaje 30 Noviembre 2014, 23:37 pm
por :Luigi
Segmentation Fault C++
Programación C/C++
marlboreano 6 3,562 Último mensaje 15 Enero 2015, 18:15 pm
por _Enko
Segmentation fault
Programación C/C++
xJajavierx 2 2,566 Último mensaje 6 Febrero 2020, 13:58 pm
por CalgaryCorpus
Segmentation Fault ayuda
Programación C/C++
GominaTilted 8 3,343 Último mensaje 23 Marzo 2020, 02:08 am
por GominaTilted
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines