-3

I am using this code to print arguments that are less or equal to 100. The problem happens when i try to compile, it always give me the error Segmentation Fault althought I do not know why this is happening. Can anyone help me to understand what is happening?

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
    printf("# args: %d\n", argc);
    printf("l1 %s\n", argv[2]);
    printf("l2 %d\n", atoi(argv[3]));
    int argumentos = argc;
    for (int i = 0; i < argumentos; i++)
    {
        if (atoi(argv[i + 1]) >= 100)
        {
            printf("%d", atoi(argv[i + 1]));
        }
        else
        {
            printf("vai dar não!");
        }
    }
    return EXIT_SUCCESS;
};
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

1 Answers1

1

The segfault happens when you access a invalid memory address. The problem is this line:

if (atoi(argv[i + 1]) >= 100)

And that:

printf("%d", atoi(argv[i + 1]));

A array of size 8, have index from 0 to 7, so the problem in your code happens when i is equal to argumentos - 1, you try to access a value that is not in your array.

riquefr
  • 260
  • 1
  • 7
  • In addition, `printf("l1 %s\n", argv[2]);` and `printf("l2 %d\n", atoi(argv[3]));` are potentially problematic if `argc` is less than 4. – Fred Larson Dec 07 '21 at 15:53