修改字符串时出现段违规

时间:2014-11-08 12:25:05

标签: c pthreads

我有一个程序的小问题,在运行时,发送给我一个分段违规显然发生在函数" ejer6"在尝试访问position [0] char * mensaje以分配9我的代码时:

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

struct structure {

    char * message;
    int integer;
};

void * ejer6(void * arg) {

    printf("Enters within");

    struct structure * turas;
    turas=((struct structure *)arg;

    turas->integer=turas->integer+1;
    turas->message[0]='9';

    printf("%d\n", turas->integer);
    printf("%s\n", turas->message);


    pthread_exit(NULL);
}

int main(int argc, char ** argv) {
    if(argc!=2) {
        printf("Enter the appropriate number of parameters\n");
    }
    else {

        pthread_t h[argc];
        struct structure turas[argc];
        int i;

        for(i=0; i<argc; i++) {
            turas[i].integer=13;
            turas[i].message="hello world";
        }

        for(i=0; i<argc; i++) {

            printf("\nThis is the value of the structure before the strand: \n");
            printf("Integer: %d \n", turas[i].integer);
            printf("Message: %s \n", turas[i].message);


            pthread_create(&h[i], NULL, ejer6, (void *)&turas[i]);
            pthread_join(h[i], NULL);

            printf("\nThis is the value of the structure after the strand: \n");
            printf("Integer: %d \n", turas[i].integer);
            printf("Message: %s \n", turas[i].message);

        }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

turas->mensaje指向您尝试修改的字符串文字。这是C中的未定义行为。使用数组或为turas->mensaje分配内存并将字符串文字复制到其中。

您可以使用strdup()(posix函数)来分配内存:

turas[i].mensaje=strdup("Hola mundo");

而不是

 turas[i].mensaje="Hola mundo";

现在,您将能够对其进行修改,并且您必须free strdup()分配的内存。