Questions on Mem Lecture 2

87 views
Skip to first unread message

Ryan Tio

unread,
Sep 13, 2020, 5:55:02 PM9/13/20
to cmpt-295-sfu
# Lecture Question
Week : 2
Slide deck name: Memory III - Heap
Question: Would it be practical to access an array with *p by using *(p + sizeof(t)), where t is the type of the array?




Ryan Tio

unread,
Sep 13, 2020, 7:04:21 PM9/13/20
to cmpt-295-sfu
Also, I have a question regarding the Bugs Lecture, specifically the examples on returning a variable from the stack.
How would you fix these bugs? Would you declare a pointer such as *p = (* int) malloc(n * sizeof(int))
and then return *p?

Arrvindh Shriraman

unread,
Sep 13, 2020, 10:18:02 PM9/13/20
to cmpt-295-sfu
Please post in Week 2 is up thread

Arrvindh Shriraman

unread,
Sep 13, 2020, 10:25:22 PM9/13/20
to cmpt-295-sfu
also list slide number 

Arrvindh Shriraman

unread,
Sep 14, 2020, 10:12:48 PM9/14/20
to cmpt-295-sfu
Not sure what you mean by the term "practical". You need to elaborate.
Further *(p+i*sizeof(t)); you need to include with index of the array you are interested in.

What is in the LHS of the expression are you trying to say
T x = *(p+i*sizeof(t))

If you want to do that then type t must be flat and shallow copyable.(https://stackoverflow.com/questions/6911688/making-a-deep-copy-of-a-struct-making-a-shallow-copy-of-a-struct).  

On Sunday, September 13, 2020 at 2:55:02 PM UTC-7, Ryan Tio wrote:

Arrvindh Shriraman

unread,
Sep 14, 2020, 10:20:37 PM9/14/20
to cmpt-295-sfu
There appears to be a typo in your example not (* int), but (int *).
1) Yes, one way of doing it is through the heap. However this assumes that the parent function will free.
foo()-> 
{         bar() { malloc} return to foo
free
}

So now you have malloc of a pointer in one function and free in another. Potential for introducing additional bugs (what if you forgot to free in foo ? )

So typically you get foo to allocate the array and pass in the pointer.

2) Alternatively you can statically or globally allocate the array. You are still returning a pointer. But now that pointer is pointing to an array that is in the global data segment. 

static int arr[10];
return arr; 

Typically any variable you declare in a function is reclaimed at the end of the function. 
Static variables are similar to global declarations. There is one copy that persists through the duration of the program. So there is no harm in returning a pointer to that.

Reply all
Reply to author
Forward
0 new messages