Heap, stack memory allocation && constant area

Source: Internet
Author: User

1 Questions:

Determine which of the following statements is correct ()
1234 const char< /code> str1[] =  "abc" const char str2[] =  "abc" const char *p1 =  "abc" const char *p2 =  "abc"
Correct answer: A your answer: F (Error)str1 and STR2 address is different, P1 and P2 address the same str1 and STR2 address the same, P1 and P2 address the same str1 and STR2 address, P1 and P2 address different str1 and STR2 address is the same, P1 and P2 address different 4 addresses are the same 4 addresses are different

Parsing: str1 and str2: allocating memory in the stack, pointing to different addresses.

The position pointed to by the P1,P2 points to the constant area.

About stacks, heap memory allocations:

1 static allocations occur when a program is compiled and connected, and dynamic allocation occurs when a program call executes.

The 2 heap is dynamically allocated, with no statically allocated heap.

The 3 stack has two modes of allocation, static and dynamic. Static allocations are done by the compiler: allocations such as local variables.

4 dynamic allocations are allocated by the function malloc, however, the stack is dynamically allocated and the heap is different, and the stack is freed by the compiler without our manual implementation.


Stack memory allocation
—————
char*
Allocstrfromstack ()
{
Char pstr[100];
return pstr;
}
Pstr is released by the system when the function returns. So the returned char* had nothing.

Heap memory allocation
—————
char*
Allocstrfromheap (int len)
{
Char *pstr;

if (len <= 0) return NULL;
Return (char*) malloc (len);
}
PSTR is to allocate memory from the heap, so even if the program exits, it is not released, so the second function returned memory no problem, can be used, but must be released with free, or a memory leak occurs.

Heap, stack memory allocation && constant area

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.