线程程序发生分段错误

时间:2015-04-08 17:55:49

标签: c multithreading pthreads ipc

我是线程程序的新手。我编写了一个用于执行线程的C程序,它反转命令行字符串并打印原始字符串和反向字符串。我的节目在这里:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
#include<string.h>

typedef struct
{
    char *input_string;
    char *rev_string;
}data;

void* rev_string(void* arg)
{
    int len = 0,index1 = 0,
    index2 = 0;
    data* names = NULL; /*bject creation*/
    names = (data*)malloc(sizeof(data));
    if( NULL == names)
    {
        printf("malloc failure\n");
        exit(1);
    }
    printf("thread recvd  = %s\n",(char*)arg);
    len = strlen((char*)arg);
    names->input_string = (char*)malloc(sizeof(char)*(len+1));
    if( NULL == names->input_string)
    {
        printf("malloc failure\n");
        exit(1);
    }
    strncpy(names->input_string,(char*)arg,len); /*copying input_string to the struct*/
    names->rev_string = (char*)malloc(sizeof(char)*(len+1));
    if( NULL == names->rev_string)
    {
        printf("malloc failure\n");
        exit(1);
    }

    for(index1 = len-1 ; index1 >= 0 ; index1--)
    {
        names->rev_string[index2] = names->input_string[index1];
        index2++;
    }


    pthread_exit((void*)names);
}

主程序:

int main(int argc,char* argv[])
{
    int no_of_strings = 0,
        len = 0,
        status = 0,
        ret = 0 ,
        index = 0;

    pthread_t id[index];  /*thread identifier*/
    void* retval = NULL; /*retval to store the value returned by thread job */

    data *strings = NULL;/*object creation*/

    if(1 >= argc)
    {
        printf(" please do enter the commands as of below shown format\n");
        printf("<exe.c> <string1> <string2> ...<string(N)>\n");
        exit(1);
    }
    no_of_strings = argc - 1 ; /* no of strings entered */
    /*creation of threads*/
    for(index = 0; index < no_of_strings ;index++)
    {
        status = pthread_create(&id[index],NULL,rev_string,(void*)argv[index + 1]);

        if(status != 0)
        {
            printf("ERROR in creating thread\n");
            exit(1);
        }

        else
        {
            printf("thread %d created\n",index+1);         }

    }

    for(index = 0 ;index < no_of_strings;index++)
    {
        ret = pthread_join(id[index],&retval);
        if(ret)
        {
            printf("Error in joining %d\n", ret);
            exit(1);
        }

        printf("the input_string = %s and its reverse = %s\n",((data*)retval)->input_string,((data*)retval)->rev_string);

    }

    //      free(retval->input_string);
    //      free(retval->rev_string);
    //      free(retval);

    pthread_exit(NULL);
    exit(0);
}

它适用于命令行参数的2个字符串。但是当超过字符串时会出现分段错误。为什么?有错误吗?帮助我。

1 个答案:

答案 0 :(得分:1)

pthread_t id[index];

id的长度为零,因为index == 0。因此,对其元素的任何赋值都是未定义的行为。使用一些正长度初始化数组,例如:

const int MAX_THREADS = 10;
pthread_t id[MAX_THREADS];  /*thread identifier*/