简体   繁体   中英

Segmentation Fault, array of pointers

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.

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.

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