Search code examples
cgccmallocfree

Why do I get 3221226356 error when calling free in C?


I'm learning C and doing some coding challenges to learn.
While doing 1 challenge I need to create a dynamic 2D char array.

I am trying to follow some other StackOverflow answers to create the 2D array dynamically.

I'm able to create it, but while trying to free the memory, I get the error 3221226356.
Below is my code:

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

    int main(int argc, char *argv[])
    {
        int n;
        scanf("%d", &n);

        char **s = malloc(n * sizeof(char *));

        for (int i = 0; i < n; i++)
        {
            s[i] = malloc(1000 * sizeof(char));
            //memset(s[i], '\0', 1000);
            scanf("%s", &s[i]);
        }

        for (int i = 0; i < n; i++)
        {
            printf("%s - %d\n", &s[i], strlen(&s[i]));
        }

        for (int i = 0; i < n; i++)
        {
            printf("Freeing %d\n", i);
            //char *tmp = &s[i];
            free(s[i]);
        }

        printf("Freeing s\n");

        free(s);

        if (argc > 1)
        {
            char xx[100];
            scanf("%s", xx);
        }
        return EXIT_SUCCESS;
    }

And an example run of the code with output:

2
xx
sss
xx - 2
sss - 3
Freeing 0

[process exited with code 3221226356]

I've tried calling free on &s[i] as well as *s[i] but both result in an error.
My compiler is GCC.

What am I doing wrong?


Solution

  • So the commends about &s[i] led me to a sort of obvious solution.
    To create a temp variable for scanf.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[])
    {
        int n;
        scanf("%d", &n);
    
        char **s = malloc(n * sizeof(char *));
    
        for (int i = 0; i < n; i++)
        {
            //s[i] = malloc(1000 * sizeof(char));
            char *tmp = malloc(sizeof(char));
            //memset(s[i], '\0', 1000);
            scanf("%s", tmp);
            s[i] = tmp;
        }
    
        for (int i = 0; i < n; i++)
        {
            printf("%s - %d\n", s[i], strlen(s[i]));
        }
    
        for (int i = 0; i < n; i++)
        {
            printf("Freeing %d\n", i);
            //char *tmp = &s[i];
            free(s[i]);
        }
    
        printf("Freeing s\n");
    
        free(s);
    
        if (argc > 1)
        {
            char xx[100];
            scanf("%s", xx);
        }
        return EXIT_SUCCESS;
    }