我遇到了一家公司的两个问题.这两个问题让我困惑.任何人都可以帮助解释答案的原因吗?
写下结果.
void Test(void){
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL){
strcpy(str, “world”);
printf(str);
}
}
Run Code Online (Sandbox Code Playgroud)
答:它会输出"世界"
写下结果.
char *GetMemory(void){
char p[] = "hello world";
return p;
}
void Test(void){
char *str = NULL;
str = GetMemory();
printf(str);
}
Run Code Online (Sandbox Code Playgroud)
Ans:输出未知,因为指针无效.
我在接受公司采访时遇到了一个问题,我无法弄清楚答案的原因.
void newArray(int* local, int size)
{
local = (int*) malloc( size * sizeof(int) );
}
int main() {
int* ptr;
newArray(ptr, 10);
}
Run Code Online (Sandbox Code Playgroud)
Ans:这会导致内存泄漏,程序不正确.
有谁知道为什么这段代码不起作用?