Help with array of char pointers.

Hello fellow C++'ers!
I have written this C code, which is sopposed to assign values to each element of the ** pointer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int main()
{
    int arrsiz=4;
    char **a = (char**)malloc( arrsiz * sizeof(char*) );

    for(int i=0; i<arrsiz; i++)
    {
        a[i] = (char*)malloc(sizeof(*a[i]) * (i+2));

        printf("sizeof(*a[i]) = %d,   ", sizeof(*a[i]));

        char tmp[i+2];
        for(int j=0; j<i+1; j++)
        {
            tmp[j]=char(65+j);
        }
        tmp[i+1]='\0';

        printf(tmp);
        printf("   ");

        a[i] = &tmp[0];

        printf(a[i]);
        printf("\n");
    }

    printf("\nAssigning ended. Starting final printing...\n\n");

    for(int i=0; i<arrsiz; i++) //Strange outputting begins...
    {
        printf("i=%d:  ", i);
        printf(a[i]);
        printf("\n");
    }

    printf("\nPrinting ended. Freeing memory...\n\n");

    for(int i=0; i<arrsiz; i++)
    {
        free(a[i]);                      //Crash! On the first freeing...
        printf("free no. %d has passed.\n", i);
    }
    printf("\ndeleting whole array...");
    delete [] a;

    return 0;
}


So this code works fine until the second loop, where it should print all the results. There, it prints the same non-null-terminated string with 6 symbols (ABCD@@) all 4 times. Strange it is, because nothing has changed after the first loop, where it printed everything fine.

Then, as you may expect, it crashes of course - at the memory freeing loop, without even freeing the first element...

What's wrong with this code?!
At line 22, you are setting a[i] to be address of the first character in tmp. However, tmp goes out of scope when the code block ends at line 26, so a[i] is now pointing to invalid memory (and not to the memory you allocated at line 8). Attempting to access the data in that memory in lines 33 and 41 result in undefined behaviour.

EDIT:
nothing has changed after the first loop


What's changed is that tmp has dropped out of scope, and the memory on the stack that it was using, has been reclaimed.
Last edited on
Oh! Thanks! Now it's working!
You're welcome :)
Topic archived. No new replies allowed.