c - in strtok how to use char* as a arguement -


in program, allocating dyanamic memory variable buffer of type 'char *' using malloc. if using strtok(buffer,"+"); giving segmentation fault. got reason stackoverflow , same problem stackoverflow. neither post giving me desired solution. can't use static memory or array type according program. my problem in strtok, in arguements if use char array working , when use char * give error. how use char * in strtok arguements.

char *buffer; int len; connection_t * conn; long addr = 0; file *fptr;  if (!ptr) pthread_exit(0); conn = (connection_t *)ptr; const char *s = "+"; char *token;   /* read length of message */ read(conn->sock, &len, sizeof(int)); if (len > 0) {  addr = (long)((struct sockaddr_in *)&conn->address)->sin_addr.s_addr; buffer = (char *)malloc((len+1)*sizeof(char)); buffer[len] = 0; /* read message */ read(conn->sock, buffer, len); printf("%s , %d \n",buffer, addr); /* first token */ token = strtok(buffer,"+"); 

last line showing segmentation fault

given comments, , including error checking, posted code needs similar to:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h>    int main( void ) {      char *buffer;     int len;     int sock;     long addr = 0;     //file *fptr;      const char *s = "+";     char *token;     struct sockaddr_in address;     ssize_t bytecount;      if( 0 > (sock = socket( af_inet, sock_stream, 0) ) )     {         perror( "socket failed");         exit( exit_failure );     }       // 'address' needs setup here     // 'bind()' needs called here     // 'connect()' needs called here      addr = ((struct sockaddr_in *)&address)->sin_addr.s_addr;      /* read length of message */     bytecount = read(sock, &len, sizeof(int));     if( sizeof(int) != bytecount )     {         fprintf( stderr, "read requested %d bytes got: %d bytes\n",                 (int)sizeof(int),                 (int)bytecount);         exit( exit_failure );     }      if (len > 0)     {         if( null == (buffer = malloc( (size_t)(len+1)) ) )         { // malloc failed             perror( "malloc buffer failed");             exit( exit_failure );         }          if( len == (bytecount = read( sock, buffer, (size_t)len ) ) )         { // correct number of bytes read             buffer[bytecount] = '\0';             printf("%s , %ld\n", buffer, addr);              /* first token */             token = strtok(buffer, s);             printf( "token: %s\n", token);         }     } } 

otherwise guessing root of problem.

please update posted code , let know result


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -