Memory usage problems (C language)

Source: Internet
Author: User
Problem: memory usage

Someone wrote a function to convert integers into strings:

Char * ITOA (int n)
{
Char retbuf [20];
Sprintf (retbuf, "% d", N );
Return retbuf;
}

If I call this function: char * str5 = ITOA (5), what is the result of str5?

Answer analysis:

The answer is uncertainty. We can be sure that it is definitely not the "5" we want ".

The retbuf is defined in the function body as a local variable. Its memory space is located at a certain position in the stack, and its scope is limited to the ITOA () function. When the ITOA () function exits, the retbuf's content in the call stack will be reclaimed. In this case, this memory address may store other content. Therefore, returning the local variable retbuf to the caller fails to achieve the expected purpose.

So how can we solve this problem? Don't worry. There are not only one solution, but more than one solution. The following describes three solutions to this problem.Solution:

1 ),Define a static char retbuf [20] In the ITOA () function. According to the characteristics of static variables, we know that this ensures that the retbuf space will not be reclaimed after the function returns, the reason is that the static variables in the function are not placed in the stack, but inProgramThe content of a part called ". BSS" won't be reclaimed because the function exits.

This solution can solve the problem, but it also leads to the ITOA () function becoming a non-reentrant function (that is, the same input must have the same output ), in addition, the content in retbuf [] will be replaced by the next call result. This method is not recommended.

2 ),In the ITOA () function, use malloc () to apply for memory for the retbuf, store the results, and then return the retbuf to the caller. Because the retbuf is located in the heap at this time, it will not be released as the function returns, so we can achieve our goal.

However, in such a case, the caller of the ITOA () function must release the retbuf when it does not need it. Otherwise, the memory will leak, if this function and the called function are both written by the same person, it is not a problem, but if not, it is easier to omit the operation to release the memory.

3 ),Define the function as char * ITOA (int n, char * retbuf), and The retbuf space is applied and released by the caller. ITOA () only stores the Conversion Result in retbuf.

This method is obviously better than the first and second methods. It not only avoids the impact of method 1 on functions, but also avoids the impact of method 2 on memory allocation and release, is currently a relatively common practice.

Extended analysis:

In fact, as far as this problem is concerned, I think everyone can immediately think of the answer. The key is to make correct and reasonable use of memory-sensitive resources. Next, let's make a simple solution for memory.Analysis:

1) The program has different memory segments, including:

. Data-the initialized global/static variables are valid throughout the software execution process;

. BSS-the global/static variables are not initialized and valid throughout the software execution process;

. Stack-function call stack, where the content is valid during function execution and is allocated and withdrawn by the compiler;

. Heap-heap, which is explicitly allocated and withdrawn by the program. If not withdrawn, the memory leakage occurs.

2) it is best to apply for and release the memory you use.

This can be said to be a principle of memory allocation and release. For example, the second solution above is to release the memory allocated by ITOA () and finally released by the caller, it is better to use the third method, where the caller applies for and releases it. In addition, this principle also means that if you want to use a pointer, you 'd better first make sure it has been directed to a valid memory zone. If not, you have to allocate it by yourself, or you have to access it illegally. Many program fatal errors are accessing a pointer that does not point to a valid memory area, which also includes a null pointer. [Page]Problem: memory allocation & sizeof

I use sizeof to calculate a pointer variable. I want to get the size of the memory block allocated by this pointer variable, OK?

Char * P = NULL;
Int nmemsize = 0;
...
P = malloc (1024 );
Nmemsize = sizeof (P );

Answer and analysis:

The answer is that it does not meet your requirements. sizeof can only tell you the memory size occupied by the pointer. The memory pointed to by the pointer. If it is allocated by malloc, sizeof cannot be known. In other words, the memory allocated by malloc cannot be queried by the memory management module afterwards. Of course, you can writeCode.

Problem: stack memory usage

What is the problem with the program running below?

Char * getstring (void)
{
Char P [] = "Hello World ";
Return P; // the compiler will give a warning
}

Void test4 (void)
{
Char * STR = NULL;
STR = getstring (); // STR content is junk
Cout <STR <Endl;
}

Answer and analysis:

The returned stack memory may be destroyed or not destroyed. However, the memory has been marked as usable by the system after the scope is exceeded, the returned pointer content should remain unchanged. It is useful in special cases. For example, it can be used to detect system memory allocation rules.

Problem: programming specifications for memory usage

I want to avoid memory usage issues as much as possible. Is there any shortcut?

Answer and analysis:

Unless you do something that has never been done before, there are shortcuts, that is, standing on the shoulders of our predecessors, and now all major companies have their own coding specifications, these specifications have accumulated a lot of experience and lessons, and have a high usage value. As these specifications are widely circulated on the Internet, I will not list them here, we recommend that you refer to Lin Rui's high quality C/C ++ programming guide.

Related Article

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.