Location of variables in the memory, C
I'm looking at exams in C from past years, and I'm came across a question I didn't fully understand. They've supplied a simple piece of code, and asked about the location of different variables in the memory. The options were heap
stack
and unknows
.
I know that automatic variables a initialized in the stack, and that dynamically allocated variables are in the heap.
So, first question - what is unknown?
For the second question here's the code and the table with the right answer:
#include <string.h>
#include <stdlib.h>
typedef struct
{
char *_str;
int _l;
} MyString;
MyString* NewMyString (char *str)
{
MyString *t = (MyString *) malloc (sizeof (MyString)); //LINE 12
开发者_StackOverflow t->_l = strlen (str);
t->_str = (char*) malloc (t->_l + 1);
strcpy (t->_str, str);
return t;
}
int main()
{
MyString ** arr = (MyString**) malloc (sizeof (MyString*)*10); //LINE 21
int i;
for (i=0;i<10;i++)
{
arr[i] = NewMyString ("item"); //LINE 25
}
// do something
// free allocated memory
return 0;
}
And here's the table with the results I didn't understand
Variable Line number Memory location
arr 21 stack
*arr 21 heap
**arr 21 unknows
arr[5] 25 heap
arr[3]->_str[2] 25 heap
*(t->_str) 12 unknows
I think I understand arr
and *arr
, but why is **arr
unknown?
The rest I couldn't answer at all, so any help would be great.
I know its long so thanks in advance...
This is a crappy exam question. The C standard does not specify how the storage is allocated -- it only specifies the semantics. Heap, stack, etc. are specifics of a particular implementation. Read about storage class and storage duration in C.
The variable arr
is allocated on the stack ("automatic variable"), but the values of the expressions *arr
and **arr
are obtained by following pointers, and in general, it is impossible to say where the memory is allocated just given the pointer to it. The similar reasoning is for the other unknown case.
About unknown: the idea behind the question is that at line 21 *arr
is allocated but not initialized. Therefore it points to some arbitrary location. Therefore the placement of **arr
is treated as unknown.
Of course, the zvrba's note about the semantics is still valid.
精彩评论