Question

This code works when these lines are commented out as shown.But if those 4 lines are uncommented,there is a SIGSEV fault-string 's' does not get initialised . How is it that a function call works at its own but not in a loop ? when the loop has nothing to do with the function's data.

  #define yes 1
    #define no 0
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    char *readline(FILE *f){
        char *buff=NULL,*newbuff=NULL,c;
        int buf_sz=1,len=0;
        int keep_going=yes;
        while(keep_going){
            c=fgetc(f);
            if(c==EOF || c=='\n'){
                keep_going=no;
                break;
            }
            if(len==buf_sz-1 && keep_going!=no){
                if(!buff){
                    buf_sz=512;
                    newbuff=malloc(buf_sz);
                }
                else{
                    buf_sz*=2;
                    newbuff=realloc(buff,buf_sz);
                }
                buff=newbuff;
            }
            buff[len++]=c;
        }
        return buff;
    }
    int main(){
        char *s;
        int l,left_mid,right_mid,lp,rp,change=no;
    //  int n;
    //  scanf("%d",&n);
    //  while(n--){
        s=readline(stdin);
        l=strlen(s);
            printf("%d",l);
        //}

            return 0;

          }
Was it helpful?

Solution

  1. buff needs to be null-terminated.

  2. scanf("%d", &n); keeps the newline.

  3. The buffer is not secured when only a newline is entered.


example to fix

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

char *readline(FILE *f){
    char *buff=NULL,*newbuff=NULL;
    int c;
    int buf_sz=512,len=0;
    buff=malloc(buf_sz);
    if(!buff) return NULL;
    while(EOF != (c=fgetc(f)) && c != '\n'){
        if(len == buf_sz -1){
            buf_sz*=2;
            newbuff=realloc(buff,buf_sz);
            if(newbuff==NULL){
                free(buff);
                return NULL;
            }
            buff=newbuff;
        }
        buff[len++]=c;
    }
    buff[len]='\0';

    return buff;
}

int main(){
    char *s;
    int n, l;
    scanf("%d%*c",&n);
    while(n--){
        s=readline(stdin);//check return value
        l=strlen(s);
        printf("%d\n", l);
        free(s);
    }
    return 0;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top