C language programming involves memory issues

Source: Internet
Author: User

In the usual C language programming often involves memory problems, the following share some common problem examples and related answers, you can learn IT500 strong interviewer to talk about algorithm surface questions .

void GetMemory (char *p)

{
p = (char *) malloc (100);
}
void Test (void)
{
char *str = NULL;
GetMemory (str);
strcpy (str, "Hello World");
printf (str);
}
What happens if I run the test function?
Answer: The program crashes.
Because GetMemory cannot pass dynamic memory, str in the Test function is always NULL. strcpy (str, "Hello World") will cause the program to crash.
Char *getmemory (void)
{
Char p[] = "Hello World";
return p;
}
void Test (void)
{
char *str = NULL;
str = GetMemory ();
printf (str);
}
What happens if I run the test function?
A: It may be garbled.
Because GetMemory returns a pointer to "stack memory", the address of the pointer is not NULL, but its original content has been cleared and the new content is unknown.
void GetMemory2 (char **p, int num)
{
*p = (char *) malloc (num);
}
void Test (void)
{
char *str = NULL;
GetMemory (&STR, 100);
strcpy (str, "Hello");
printf (str);
}
What happens if I run the test function?
Answer: (1) can output Hello; (2) Memory leak

void Test (void)
{
Char *str = (char *) malloc (100);
strcpy (str, "Hello");
Free (str);
if (str! = NULL)
{
strcpy (str, "World");
printf (str);
}
}
What happens if I run the test function?
A: Tampering with the contents of the dynamic memory area, the consequences are difficult to pre-
the material is very dangerous.
because it is free (str), then STR becomes a wild pointer,
The if (str! = NULL) statement does not work.

To learn more programming language Tutorials please login e mentor Web.

C language programming involves memory issues

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.