CrypticStorm
CrypticStorm

Reputation: 560

C Segmentation Fault from argc

I'm currently trying to code my CS lab and am getting a Segmentation fault that I can not see. Am I doing something stupid or what? Code should take the command line args ("blah.exe hello world") and output them with a banner around them. Our class has no prior knowledge of C, but prior courses in data structures.

Example output

===============
= hello world =
===============

Source: compiled with gcc -std=c99 -Wall bannerize.c

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

int main(int argc, char* argv[]) {
        if(argc <= 1) {
                return EXIT_FAILURE;
        }

        printf("TEST");
        int row_length = argc + 3; //3 for space after last word and 2 extra border chars
        for(int i = 1; i < argc; i++, row_length += strlen(argv[i]));

        printf("TEST2");
        char c;
        while((c=getchar())!=EOF) {
            printf("TEST3");
            for(int i = 1; i < argc; i++, printf("%c", c));
            printf("\n");

            printf("%c ", c);
            for(int i = 1; i < argc; i++, printf("%s ", argv[i]));
            printf("%c\n", c);

            for(int i = 1; i < argc; i++, printf("%c", c));
            printf("\n");
    }

    return EXIT_SUCCESS;
}

Works fine for simply running with no parameters, but adding any command line arguments is giving a segmentation fault before it prints anything.

Upvotes: 1

Views: 2253

Answers (1)

cnicutar
cnicutar

Reputation: 182754

for(int i = 1; i < argc; i++, printf("%s ", argv[i]))

This is a weird and twisted way to write a for. Consider what happens when i == argc - 1. You increment it and then you access argv[argc]. Which is necessarily NULL.

Instead of this cryptic (ZING!) way of writing the for, try using an actual body:

for(int i = 1; i < argc; i++) {
    printf("%s ", argv[i]);
}

The catch is that the body is executed only if the condition (i > argc) holds.

Upvotes: 4

Related Questions