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