Why did a dynamic array work without the use of malloc?

3

The following code snippet follows:

int main(void)
{
    int tam, vet[tam];
    printf("\ndigite tam: ");
    scanf("%d", &tam);
    return 0;
}

I did not know this worked because I'm typing the vector size at runtime. For me, this was one of the features of malloc , because in this case, I expected the user to enter, take the typed size and make a malloc with that size. But by the way, does C already do this automatically?

What happens in this case? What would be most appropriate to do in cases with this?

    
asked by anonymous 07.10.2014 / 18:54

2 answers

7

Your code does not allocate as you think, you are making a serious mistake. This code is far from doing what you think it is.

You are reserving memory for vet with undetermined amount of elements. Yes, because you declared tam but did not put any value to it. Then the value that is in the memory location of tam will be the size of vet . Certainly the information that is there is crap. It may be zero and do not reserve memory for vet . It may be a very large number and reserve several KB or MB of memory without you needing it.

You only get a value for tam after the vet variable is declared.

What you may not have understood is that C lets you do what you want with memory. If it works by coincidence, poor of its application. In C you have to make sure everything is working properly. Taking a test and finding that it is working is a danger. It worked in a specific situation. The next run may not work, running on another computer may not work. Although this is especially important in C, it is something that holds true for any language. Testing and working does not guarantee that the program is correct , especially in C where there is a lot undefined behavior . Unfortunately there is a widespread thought that thinks a simple test is enough.

A possible correct implementation:

#include <stdio.h>

int main(void) {
    int tam;
    printf("\ndigite tam: ");
    scanf("%d", &tam);
    int vet[tam];
    printf("%d", vet[0]);
}

See running on ideone . And in Coding Ground . Also I put it in GitHub for future reference .

Notice that I'm just doing what you intended. I'm not storing anything in this array .

See a example on Wikipedia how to allocate in stack . p>     

07.10.2014 / 19:05
3

Arrays with variable length are allowed from C99 , as you can see here .

According to the same link, these arrays work like any other in size that is a constant expression, so it has the same function as

int v[10];

In addition, they do not function as an array allocated with malloc , since they are allocated in heap while variable-size arrays are allocated on the stack, but with unknown address at compile time.

    
07.10.2014 / 18:56