Assigning value to char pointer

Hello,
I am not able to understand the following concept

Main.cpp
1
2
3
4
5
6
7
8
int main()
{
   char* temp=(char*)malloc(32*sizeof(char));
   temp[15]=66; 
   char temp1[32];  // i apologise for char* temp1
   temp[15]=66;
   return 0;
}


when i print temp it shows "" , while for temp1 it shows |||||||||||||B||||||||||

what i am not able to understand is, in case of temp how do we assign values.

help appreciated
amal
Last edited on
I think you need to read your code again and compare it to the description of the problem you have given - You will see that the code and your description of the problem do not match up at all.
Last edited on
@guestgulkan --> i apologise for char* temp1
In both cases you are leveraging behavior that is not defined in C/C++.

When you malloc() memory, the memory you get is uninitialized and could contain anything at all. When you allocate variables on the stack (as in temp1) again,
unless explicitly initialized, the memory could contain anything at all.

Your code only initializes one element (char) of a multi-char array, and so the only thing you can rely on is that the 15th element of each array contains the value 66. All other elements are uninitialized and therefore their values are undefined.

What you are seeing probably is that "temp" happens to be all zeroes when you allocate it and hence when you print it, it looks like a zero-length string. That it is all zero is not something you can rely on. What you are seeing is the operating system giving you a memory page that is all zeroes (this is a security measure).

In the case of the stack variable, it is again likely that when the operating system initially allocate the memory pages for your program stack they contained all zeroes.
But chances are the stack has already been used by the C++ runtime during program startup and by malloc itself, and so the part of the stack used to allocate temp1 has already been written to, and you are seeing that.

Not sure what your second question is.
Topic archived. No new replies allowed.