Bernard Meurer Bernard Meurer - 3 months ago 8
Linux Question

Irregular segmentation fault

I'm attempting to run the following code:

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

int main(int argc, char const *argv[]) {
/* code */
char senha [256];
if (argv[1] != NULL)
{
strcpy(senha, argv[1]);
}
char frase [256];
printf("Insira a frase: \n");
scanf("%s", frase);
int sizeS = (int)strlen(senha);
int sizeF = (int)strlen(frase);
char fraseout [sizeF+1];
int i;
int j;
for (i=0; i<=sizeF-1; i++)
{
if(j>=sizeS)
{
j=0;
}
int valF = (int)frase[i];
int valS = (int)senha[j];
valF = 32 + ((valF - 32) + (valS - 32)) % (128-32);
fraseout[i] = (char)valF;
j++;
}
fraseout[sizeF] = '\0';
printf("\"%s\" -> \"%s\"\n", frase, fraseout);
return 0;
}


When I attempt to run this on my Ubuntu 15.04 it compiles and runs perfectly. When I try to run it on a OSX Yosemite it also compiles and run flawlessly. If I, however, compile and run it on a CS50 VM although the compilation runs fine I get a Segmentation Fault error on Running. Why is this happening and why only on one singular OS?

Answer

Possible issues, with irrelevant lines removed. The uninitialized ones are likely your problem.

argv[1] != NULL is safe with C89, but is obscure and might not be on noncompliant compilers. Checking argc is more typical.

senha is left uninitialized i f the argument is not passed, which may result in buffer overflows later.

        char senha [256];
        if (argv[1] != NULL)
                strcpy(senha, argv[1]);

Not checking the size of the buffer for input, use scanf("%255s", frase);

Not checking the return value of scanf, frase will be left uninitialized if it fails, which may result in buffer overflows later.

        char frase [256];
        scanf("%s", frase);

VLAs not in C89, but are in C99 and provided as an extension in GNU C89, which is the default used by gcc. This may fail to compile with strict C89 compilers.

        int sizeF = (int)strlen(frase);
        char fraseout [sizeF+1];

Not initialized.

    int j;

This computation may yield a ", resulting in improperly quoted output.

                valF = 32 + ((valF - 32) + (valS - 32)) % (128-32);
                fraseout[i] = (char)valF;
        printf("\"%s\" -> \"%s\"\n", frase, fraseout);
Comments