-2

I'm not a expert in C, in fact, I hate it, but I have to do this project in this lenguage for my university. Well, when I have gone to test my code, I had a surprise with this error, "Segmentation fault". I was looking for internet and reading people with the same problem and I couldn't solve it.

So, this is my code:

typedef struct evento{
    char* tipo; //baja, alta o evento
    char* tema; //tema al que pertenece
    char* valor;
    int puerto;
    struct sockaddr_in *dir;
}evento;

int generar_evento(const char *tema, const char *valor) {

//Socket()

int sock;

sock = socket(AF_INET, SOCK_STREAM, 0);

if (sock < 0){
perror("Error en socket() en Editor");
exit(1);
}

//Preparar mensaje

evento evt;
strcpy(evt.tipo, "evento");
strcpy(evt.tema, tema);
strcpy(evt.valor, valor);

The code follows but is not important because I was testing it and the error is in:

evento evt;
strcpy(evt.tipo, "evento");
strcpy(evt.tema, tema);
strcpy(evt.valor, valor);

I need that the generar_evento's parametres (const char *tema, const char *valor) be copied in a struct evento but when I tried to do it the error appered.

Thanks!

juanjo
  • 9
  • 4

1 Answers1

0
char* tipo; 
char* tema;
char* valor;

Those char* need memory.

Give them some with malloc(strlen("the string you want to cpy") + 1);

And don't forget to free() them when you don't need them anymore.

Sébastien S.
  • 1,444
  • 8
  • 14