0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
    char name[100];
    long size;
    char mode[8];
    char uid[8];
    char ouid[8];
    char size1[12];
    char time[12];
    char checksum[8];
    char type[1];
    char linkname[100];
}HEADER;


int main(int argc, char **argv)
{
    for(int i = 1; i <= argc; i++) argv[0,1,2] are program name, c, tar output file
    {
        HEADER header;
        strcpy(header.name, argv[i]); // saving the name of the file
        FILE *fin = fopen(argv[i], "rb");
        if(fin == NULL)
        {
            fprintf(stderr, "File not found.\n");
            exit(1);
        }
        fseek(fin, 0L, SEEK_END);
        header.size = ftell(fin);
        printf("%s is %ld bytes long\n", header.name, header.size);
        fseek(fin, 0L, SEEK_SET);
        fclose(fin);
    }

    return 0;
}

I want to store the number of bytes and the name of the files provided as command line arguments, but I'm getting a segmentation fault. I ran a debugger and strcpy is the problem, name has fixed size so I don't need to allocate memory. Can you help me?

0

2 Answers 2

2

The problem is i <= argc as the loop condition. The argc argument is the number of elements in the argv array, not the top valid index. Its semantics is very much similar to the string length returned by strlen.

But what's causing the crash is that the argv element at index argc (i.e. argv[argc]) is a null pointer. And you try to use this null pointer in several places (when i is equal to argc).

You need to use i < argc instead as the loop condition as well.

Sign up to request clarification or add additional context in comments.

Comments

1

argc has the number of parameters passed in the command line, +1 for the program name. This means that if the app is started with

app_name p1 p2

argc will be 3, but the index in the argv array is 0, 1 and 2. In the for loop, you are looping from 1 until argc, it should be from 1 to argc-1, because arrays in C starts from 0. If you replace <= with <, loop will iterate correctly.

for(int i = 1; i < argc; i++) argv[0,1,2] are program name, c, tar output file
    {
        HEADER header;
        strcpy(header.name, argv[i]); // saving the name of the file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.