Search code examples
cpointerssegmentation-faultcommand-line-argumentsfunction-declaration

c- segmentation fault error due to calling a function that has text that user put in the terminal


Summary

I am trying to pass the text that user has put in the terminal and pass it to the function named printString(). I don't fully understand C but I think I has to do with the pointer not being in the heap. Any help would be appreacitaed!

#include <stdio.h>
void printString();
int main (int argc, char* argv[]) {
        int commandAmount = 1;
        while (commandAmount < argc) {
        printString(commandAmount, &argv);
        }
        return 0;
}
void printString(int commandAmount, char* argv[]) {
        printf("the word is %s," , argv[commandAmount]);
}

./shortExample example
Segmentation fault (core dumped) 

Solution

  • The prototype void printString(); does not match the actual implementation. It should have been:

    void printString(int commandAmount, char* argv[]);
    

    You could also skip the prototype and just implement the function before main. Your loop while (commandAmount < argc) seems to not have any way to finish since you never increase commandAmount. This can cause undefined behavior and with such, your program may crash or do just about anything. I suggest making a for-loop to fix that.

    Example:

    #include <stdio.h>
    
    void printString(int commandAmount, char* argv[]) {
        printf("the word is %s,", argv[commandAmount]);
    }
    
    int main(int argc, char* argv[]) {
        for(int commandAmount = 1; commandAmount < argc; ++commandAmount) {
            printString(commandAmount, argv);
        }
    }
    

    or in the way you structured it:

    #include <stdio.h>
    
    void printString(int commandAmount, char* argv[]); // corrected
    
    int main(int argc, char* argv[]) {
        int commandAmount = 1;
        while (commandAmount < argc) {
            printString(commandAmount, argv);
            ++commandAmount;                           // needed
        }
    }
    
    void printString(int commandAmount, char* argv[]) {
        printf("the word is %s,", argv[commandAmount]);
    }