I am attempting to understand Dynamic Memory Allocation on a deeper level. This code is NOT meant to work correctly. This is just destructive testing for my own understanding.
Hello all. I'm trying to learn a bit here and I'm struggling. I'm under the assumption that when I create a string such as
char test[] = "Hello World!!!";
then, during compile time, there is 15 bytes allocated to memory for the string above plus the null character. If I were to need a string that is twice as large, I could then simply do this
char *testPtr = malloc(strlen(test) * 2);
and 30 bytes would be allocated to the heap and all is good. However, I believe this is incorrect thinking. Or, there is a further bit of information that I don't have yet. The source of this confusion is this code
char *test = malloc(1);
strcpy(test, "Hello World!!!");
printf("\n\n%s\n\n", test);
free(test);
If I run this, it, in fact, gives me the string "Hello World!!!" This doesn't make any sense to me at all. I understand that char x = 'c';
allocated 1 byte to the stack. But, the single byte is for 'c' but where is x stored? If I allocate memory to a pointer, how is that memory usable? If I were to write char *test = malloc(4);
how many characters(1 byte) are able to go there? Are they all stored on the heap, the stack, or a mix of both? Why is the code malloc(1) code above allowing more than 1 character in that pointer? If a pointer holds 8 bytes, what exactly is using the 8 bytes? Is that 8 bytes where the variable name is or what the data the pointer is holding is? And finally, where are the variable name+type stored vs the data and how is that memory allocated, ie what is the programmer able to control and manipulate? Sorry for the question dump but a lot of this kind of goes together. Thank you ahead of time to all the C wizards that can answer these questions!