0

my main function needs to collect array size from user and fill it with strings, to then send out to functions - my main appears to crash after recieving a single string - I believe the error is due to temporary_string - when it does work I get no indication the arrays actually enter the function and the output is the same as the input - I don't know why.

int main() {
    int n = 0, rule = 0;
    char* temporary_string="";
    printNumStringsInputMessage();
    scanf("%d", &n);
    printStringsInputMessage(n);
    char** arr_of_strings= malloc(n * sizeof(char*));
    for (int l = 0; l < n; l++)
    {
        scanf("%s", temporary_string);
        arr_of_strings[l] = malloc((strlen(temporary_string) * sizeof(char)));
        strcpy(arr_of_strings[l], temporary_string);
        strcpy(temporary_string,"");
    }
    printRuleOfComparisonInputMessage();
    scanf("%d", &rule);
    return (0);
}
kal_elk122
  • 143
  • 6
  • It does work meaning after some tinkering with the code, albeit it does send warnings – kal_elk122 Jan 27 '21 at 14:36
  • yes I think it does, although it's theoretical and I'm not sure I would've been able to correct my program without specific attention – kal_elk122 Jan 27 '21 at 14:57

2 Answers2

1

you cannot change this value: char* temporary_string="";, it's constant and it's same as const char* temporary_string="";, this causes the segmentation fault. use instead an array of characters.

ic_Engineer
  • 313
  • 3
  • 12
0

You must not modify string literals.

Instead of

    char* temporary_string="";

You should allocate an modifyable array like this:

    char temporary_string[102400];

It is also a good practice to limit the maximum size to read to avoid buffer overrun.

        scanf("%s", temporary_string);

should be

        scanf("%102399s", temporary_string);

if you use the above array. The maximum length is the length of array minus one because the laste element is for terminating null-character.

Also you must allocate also for terminating null-character. This means that this line

        arr_of_strings[l] = malloc((strlen(temporary_string) * sizeof(char)));

should be

        arr_of_strings[l] = malloc(((strlen(temporary_string)+1) * sizeof(char)));
MikeCAT
  • 73,922
  • 11
  • 45
  • 70