0

Why do I get the Segmentation Fault error? I've documented a lot but couldn't clarify this.

char * sir=malloc(50*sizeof(char));
char * aux;
int i;

for(i=1;;i++)
{
    fgets(aux, 50, stdin);

    if(strcmp(aux,"END")==0)
        break;
    else
    {
        sir[i]=malloc(50 * sizeof(char));
        strcpy(aux,sir[i]);
    }
}

If I use static allocation, then I get an infinite loop.

2
  • 2
    No alloc for *aux so UB:( Commented Dec 5, 2015 at 14:09
  • 1
    1) not allocated for aux 2) fgets include newline. strcmp(aux,"END\n") instead of. 3) type of sir is char *. char ** sir=malloc(64*sizeof(char*)); instead of. and strcpy(aux,sir[i]); --> strcpy(sir[i],aux); Commented Dec 5, 2015 at 14:09

1 Answer 1

1

Pointer aux was not initialized and has indeterminate value

char * aux;

Thus in this loop the attempt to write data using the pointer

for(i=1;;i++)
{
fgets(aux, 50, stdin);
//...

results in undefined behaviour of the program.

Maybe it is a typo and you meant str instead of aux Nevertheless in any case this statement

sir[i]=malloc(50 * sizeof(char));

does not make sense.

Also this cpmparison is wrong

if(strcmp(aux,"END") == 0)

because the string read by using fgets can contain a new line character.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.