I'm trying to understand what's wrong with my code. I have a string composed by words inserted by user input. I've terminated the string so it should be ok.
Then I use another cycle to reverse the direction of the words. But when I call STRLEN on the last word of the string, it gives me segmentation fault. (the reversal part is not done yet, since i'm stuck with this problem).
Why?
Here is the code:
char *frase, c;
int i=0;
int d=1;
frase = (char*)malloc(sizeof(char));
printf("Insert phrase: ");
while(c != '\n') {
c = getc(stdin);
frase = (char*)realloc(frase,d*sizeof(char)); //dynamic allocation
frase[i] = c;
d++;
i++;
}
//at the end i terminate the string
frase[i]='\0';
printf("\nInserted phrase: %s\n",frase);
// here I start the reversal, first of all I separate all the words
char *pch;
char s[2] = " ";
int messl=0;
pch = strtok (frase,s);
printf ("%s\n",pch);
messl += 1 + strlen(pch);
printf ("Lung stringa = %d\n",messl);
char *message = (char*) malloc(messl);
while (pch != NULL) {
pch = strtok (NULL, s);
printf("%s\n",pch);
messl += 1 + strlen(pch); //in the last cycle of the loop I get the error
}
//printf ("%s\n",message);
return 0;