简体   繁体   中英

Segmentation fault when using strlen on user input string

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;

In your code.

 while(c != '\n')

at the very first iteration, c is uninitialised. It invokes undefined behaviour to use the value of an automatic local variable which has not been initialized explicitly.

getc() returns an int which , at times, may not fit into a char . Change the type of c to int .

That said, as you mentioned in your question, that you're getting segfault from strlen() , you need check for the non-NULL value of the passed pointer to strlen() . Add the NULL-check to pch immediately after tokenizing.

The main problem is:

while (pch != NULL) {
    pch = strtok (NULL, s);
    printf("%s\n",pch);
    messl += 1 + strlen(pch); 

When strtok returns NULL , you go on to call printf and strlen on it. You need to immediately test pch upon calling strtok . For example the loop structure could be:

while ( (pch = strtok(NULL, s)) != NULL ) {

There are various other problems too, as other answerers/commentors have noted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM