Fórum Root.cz

Hlavní témata => Vývoj => Téma založeno: Rad1m 02. 02. 2014, 13:18:34

Název: C: Segmentation fault (core dumped)
Přispěvatel: Rad1m 02. 02. 2014, 13:18:34
Potreboval bych pomoc s odchycenim chyby pri pouziti argc a argv.

pokud program spustim s argumentem, napriklad ./caesar 50, vse funguje. Pokud ale pouziju jen ./casear , tak dostanu hlaseni: Segmentation fault (core dumped), ja bych ale potreboval, aby program fungoval i v pridape, ze uzivatel zapomene zadat argument

zde je kod:

int main(int argc, string argv[])

{
    int uc, lc;
    int cipher = atoi(argv[1]);
   
    if (argc < 1){
        printf("Usage: /home/cs50/pset2/caesar <key>\n");
        return(0);
    }
   
    if (cipher < 0){
        printf("Key must be a non-negative integer.\n");
        exit(0);
    }
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: Filip Frank 02. 02. 2014, 13:30:32
Asi by to chtelo nejdrive podminku zda nejaky argument je zadan ?  :)
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: Rad1m 02. 02. 2014, 13:46:23
zkousel jsem

if (argc < 1){
        printf("no argument");
        return(1);
}

ale stale to vypisuje: Segmentation fault (core dumped)
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: tadeas 02. 02. 2014, 13:52:28
    int cipher = atoi(argv[1]);

přistupuje k argv dřív, než ověří, že tam něco je.
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: Rad1m 02. 02. 2014, 14:14:52
stale konci s: Segmentation fault (core dumped)

int main(int argc, string argv[])

{
    int uc, lc, cipher;
   
    if (argc < 1){
        printf("you must enter an argument\n");
        return(1);
    }
   
    if (atoi(argv[1]) < 0){
        printf("Key must be a non-negative integer.\n");
        return(1);
    }
    else{
        cipher = atoi(argv[1]);
    }
}
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: Rad1m 02. 02. 2014, 14:23:13
uz jsem na to prisel, musi tam byt 2 misto 1

if (argc < 2){
        printf("you must enter an argument\n");
        return(1);
Název: Re:C: Segmentation fault (core dumped)
Přispěvatel: Ondra Satai Nekola 02. 02. 2014, 17:27:25
Na tomhle prikladu je pekne videt, ze se hodi pouzivat debugger. Kdyz te to neprasti do oci rovnou pri pohledu do kodu (coz po chvili programovani v takovemhle pripade nejspis nastane), tak hned uvidis, kde je problem, pokud pouzijes vhodny nastroj.