Malloc which covers an area allocated to the compilation
I have a C source code in which I declare:
Code:
main()
{
float variable=0;
float * tab;
tab=malloc(10000*sizeof(float));
/* Function where I pass variable & tab that contains a loop assigning values to tab[i] */
}
For now I put a malloc (10000) instead of [] because I intend to eventually make the size variable at runtime.
The problem I encounter is that "variable" is allocated to address 0X0013fe9C, while the address is pointing 0X0013fe0 tab. Result: the execution of my 4th loop (tab [3] points to 0X0013fe9C, because in my case sizeof (float) = 4) crushes "variable".
What I do not understand is that the memory location of "variable" is reserved for the compilation, while that by pointing tab via the malloc is reserved for the execution. I thought the two were separated. I'm using VS Express 2008.
Re: Malloc which covers an area allocated to the compilation
In this case, variable and tab spaces are stored on the stack. So the exact address is not determined until run-time.
If these fields had been declared outside a function, then they would have been declared on the heap and had an address fixed at compile time (which was then adjusted by the loader when loading the program memory).
A small error is not to cast the return of malloc (), in fact, the compiler should issue a warning. Write:
tab=(float *)malloc(10000*sizeof(float));
Then, there is no reason why tab [x], where x between 0 and 99999, is encroaching on other variables, because the notation with the brackets is equivalent to (address found in tab) + x, and not (address tab) + x.
Re: Malloc which covers an area allocated to the compilation
thank you, I was correct, of course, "variable" is, therefore, are not static location is reserved for the entry in the block on the stack.
But I still reserve my malloc, which already used a ... and I really do not understand why.
Re: Malloc which covers an area allocated to the compilation
tab is equal to 0X0013fe0, which is close to the address of variable. But what is the address in the location 0X0013fe0
Re: Malloc which covers an area allocated to the compilation
@Bull50, you do not used &tab instead of a tab by accident?
@Lemog, it is not necessary - and many (*) consider it bad style to do - to cast the result of malloc in C (that would be necessary in C++, a warning or an error on this line C is usually the result of another problem, forget to include for example).
(*) I do not, but I know I am rather in the minority.