Once the function is executed, wouldn't the memory used for pc be freed?
In that case, there would no longer be any array, just a pointer to char
called pc. Dereferencing pc shouldn't give me any value because I freed up the memory. However, I can still call this function in main() and cout-ing it prints out every element in an array I thought was deleted since its local to the build_str() function. Can you please explain how I understood this incorrectly?
1 2 3 4 5 6 7 8 9 10 11 12
char* build_str(char ch, int n)
{
char* pc = newchar[n+1];
char* pq = pc;
for (int i = 0; i<n; i++)
{
*pq=ch;
pq++;
}
*pq='\0';
return pc;
}
You should see the difference between stack variable char* pc and the actual heap memory used up when calling newchar[n+1]. This are in fact two chunks of memory.
pc is a pointer, so it takes up 32 or 64 bits of memory in usual desktop. It holds the address to the heap location where newchar [n+1] got created, and not the letters you are couting.
newchar [n+1] is unnamed array that takes up n+1 * size of char in memory and each cell of the array holds one letter you are couting.
When function exits, pc is freed - address of unnamed heap array may be ereased, but the unnamed array itself still is in the same place - that's how new keyword works. The fact that you are writing '\0' to first element of that array does not change the state for any other element - they do not get destroyed or freed, untill you use delete[].