0
votes

"*Program received signal SIGSEGV, Segmentation fault.
0x000000000040073b in concat (nextstr=0x7fffffffee66 "the",
longstr=0x7fffffffe750 "", i=0x0) at main.c:24
24 printf("%c -> %c\n", nextstr[j], longstr[*i]);
(gdb)"

// define max for command line
#define MAX_CHARS 1000
#include <stdio.h>
int concat(char[], char[], int *);
void printreverse(char[], int);

int main(int argc, char *argv[])
{
    char longstring[MAX_CHARS] = { '\0' };
    int i = 0, j;

    if (argc < 2)
    {
        printf("%s requires command-line args\n", argv[0]);
        return 1;
    }

    for (j = 1; j <= argc; j++)
    {
        if (concat(argv[j], longstring, i))
            return 1;
    }

    i--;
    longstring[i] = '\0';    //delete trailing space
    printf("%s\n", longstring);
}

int concat(char nextstr[], char longstr[], int *i)
{
    int j = 0;

    while (nextstr[j] != '\0')
    {
        printf("%c -> %c\n", nextstr[j], longstr[*i]);
        longstr[*i] = nextstr[j];

        (*i)++;
        j++;

        if (*i > MAX_CHARS)
        {
            printf("Error: Input is too long!\n");
            return 1;
        }
    }

    if (j > 0)
    {
        if ((*i) + 2 > MAX_CHARS)
        {
            printf("Error: Input is too long!\n");
            return 1;
        }

        longstr[*i] = ' ';
        longstr[(*i) + 1] = '\0';
        (*i)++;
    }

    return 0;
}

Pointer error most likely

"This takes a command line argument is checks the length but there's a seg fault"

I think the error is on line 33 but I can't figure out how to fix it

1
People are more likely to look/help with proper code indenting. Also, you've interspersed your commentary with the code. The trailing part of your code is outside the code block which is why it comes up yellow [as in a quoted passage], which is kicked off by a > outside of a code block. - Craig Estey
In main, you are passing i to concat(). First i is an int, not an int*, Second since i is initialized to 0, you are passing a null pointer. So (*i)++ with a null pointer would generate a seg fault. - Marker
I don't really know c at all i'm learning so can you show me in the code with comments - Michael Innamorato
I don't have to allocate memory using malloc to create memory for the pointer to hold the char - Michael Innamorato
Try changing this line "if(concat(argv[j], longstring, &i)) return 1;" in main(). The &i will pass the address of i to concat() - Marker

1 Answers

1
votes

The main problem that is causing the crash is in your for loop:

for(j = 1; j <= argc; j++){
    if(concat(argv[j], longstring, i)) return 1;
}

Since concat's third parameter is an int *, you need to pass a pointer to i. Also, you are iterating through the loop one too many times. If argc is 2, then the program name is in argv[0], and your argument is in argv[1]. So, change the loop to this:

for(j = 1; j < argc; j++) {
    if (concat(argv[j], longstring, &i))
        return 1;
}