2

I have a small problem with a program that when running, sends me a segmentation violation apparently occurs in the function "ejer6" when trying to access the position [0] of char * mensaje to assign 9 my code :

#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;
}
P.P
  • 117,907
  • 20
  • 175
  • 238
cheroky
  • 755
  • 1
  • 8
  • 16
  • what's the point of creating threads if you execute them sequentially? – Karoly Horvath Nov 08 '14 at 12:33
  • You may want to have a look [here](http://meta.stackoverflow.com/questions/266563/do-non-english-words-increase-the-probability-of-receiving-downvotes/) to understand how non-english code reduces your chance to get good answers. – nvoigt Nov 08 '14 at 12:37

1 Answers1

1

turas->mensaje points to a string literal, which you are attempting to modify. This is undefined behaviour in C. Use an array or allocate memory for turas->mensaje and copy the string literal into it.

You can use strdup() (posix function) to allocate memory:

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

instead of

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

Now, you will be able to modify it and you'll have to free the memory allocated by strdup().

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 2
    and "malloc" would be something : turas[i].mensaje = malloc(argc * 12); – cheroky Nov 08 '14 at 13:08
  • Not sure why include a factor `argc`. If you prefer to use `malloc()`, allocate enough memory for string and use strcpy()` to copy the string: `turas[i].mensaje=malloc(strlen("Hola mundo")+1); strcpy(turas[i].mensaje, "Hola mundo");` you should also check if `malloc()` fails. – P.P Nov 08 '14 at 13:13