在strtok如何使用char *作为争论

时间:2016-01-16 15:44:49

标签: c string segmentation-fault malloc string.h

在我的程序中,我使用malloc将dyanamic内存分配给'char *'类型的变量缓冲区。然后,如果我使用strtok(buffer,"+");,它会给出分段错误。我得到了Stackoverflow和同样问题Stackoverflow的原因。但是这两个帖子都没有给我一个理想的解因为根据我的程序我不能使用静态内存或数组类型。 我的问题是在strtok,在争论中,如果我使用char数组然后正常工作,当使用char *然后给出错误。如何在strtok争论中使用char *。

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 and %d \n",buffer, addr);
/* get the first token */
token = strtok(buffer,"+");

显示分段错误的最后一行

1 个答案:

答案 0 :(得分:1)

给出评论并包括错误检查,发布的代码需要类似于:

#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 to be setup here
    // 'bind()' needs to be called here
    // 'connect()' needs to be 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 but only got: %d bytes\n",
                (int)sizeof(int),
                (int)bytecount);
        exit( EXIT_FAILURE );
    }

    if (len > 0)
    {
        if( NULL == (buffer = malloc( (size_t)(len+1)) ) )
        { // then malloc failed
            perror( "malloc for buffer failed");
            exit( EXIT_FAILURE );
        }

        if( len == (bytecount = read( sock, buffer, (size_t)len ) ) )
        { // then correct number of bytes read
            buffer[bytecount] = '\0';
            printf("%s and %ld\n", buffer, addr);

            /* get the first token */
            token = strtok(buffer, s);
            printf( "token: %s\n", token);
        }
    }
}

否则我们只是猜测问题的根源。

请更新发布的代码并告知我们结果