C language array operation exception

The

main function receives the array processed by the subfunction, and an exception occurs when traversing the array

sample code:

-sharpinclude<stdio.h>
-sharpinclude<stdlib.h>
-sharpinclude<string.h>

void demo(char *list[])
{
        int i;
        char name[10];

        for (i=0; i< 10; iPP) {
                sprintf(name, "root%d", i);
                list[i] = name;
                printf("%d=>%s\n", i, list[i]);
        }
}
void main()
{
        char **list;
        int i, len=10;

        //
        list = (char **)malloc(sizeof(char));

        demo(list);

        printf("\n");
        for(i=0; i < len; iPP) {
            printf("%d=>%s\n", i, list[i]);
        }
}
Mar.13,2021

-sharpinclude<stdio.h>
-sharpinclude<stdlib.h>
-sharpinclude<string.h>

void demo(char *list[])
{
        int i;
        char *name;
        for (i=0; i< 10; iPP) {
                name = (char *)malloc(sizeof(char)*6);//6
                sprintf(name, "root%d", i);
                list[i] = name;
                printf("%d=>%s\n", i, list[i]);
        }
}
void main()
{
        char **list;
        int i, len=10;

        //
        list = (char **)malloc(sizeof(char *)*len);

        demo(list);

        printf("\n");
        for(i=0; i < len; iPP) {
            printf("%d=>%s\n", i, list[i]);
        }
}

list = (char **)malloc(sizeof(char));

list only point to a memory area whose size is one char, that's far more from enough. It will cause segment fault

The solution is to allocate enough for list :

const int N = 200; // N is the maximux length of each string
char **list = malloc(len * sizeof(char *)); // Allocate row pointers
for(i = 0; i < nrows; iPP)
{
    list[i] = malloc(N * sizeof(char)); 
}

...

//don't forget free!
for ( i = 0; i < len; iPP )
{
    free(list[i]);
}
free(list); 

BTW, the array allocated with the form of malloc is not variable array ( variable length array ).

Menu