动态内存分配经典面试题

120 阅读1分钟

动态内存分配经典面试题

  • void GetMemory(char* p) {
        p = (char*)malloc(100);
    }
    void Test(void) {
        char* str = NULL;
        GetMemory(str);  // 不是传址调用,而是传值调用
        strcpy(str, "hello world");  //str还是空指针
        printf(str);
    }
    int main() {
        Test();
        return 0;
    }
    
    // 改正1
    char* GetMemory(char* p) {
        p = (char*)malloc(100);
        return p;
    }
    void Test(void) {
        char* str = NULL;
        str = GetMemory(str);
        strcpy(str, "hello world");
        printf(str);
        free(str);
        str = NULL;
    }
    int main() {
        Test();
        return 0;
    }
    
    // 改正2
    void GetMemory(char** p) {
        *p = (char*)malloc(100);
    }
    void Test(void) {
        char* str = NULL;
        str = GetMemory(&str);
        strcpy(str, "hello world");
        printf(str);
        free(str);
        str = NULL;
    }
    int main() {
        Test();
        return 0;
    }
    
  • char* GetMemory(void) {
        // 该数组实在栈空间上开辟的,出了该函数
        // p的空间就还给操作系统了
        // 返回这个地址没有意义,再去访问就是非法访问
        char p[] = "hello world";
        return p;  // 返回栈空间地址的问题
    }
    void Test(void) {
        char* str = NULL;
        str = GetMemory();
        printf(str);
    }
    int main() {
        Test();
        return 0;
    }
    
    // 改正
    // 类似于上一题第一种方法
    char* GetMemory(void) {
        char* p = (char*)malloc(100);
        p = "hello world";
        return p;
        // 为什么出了这个函数,p还有意义呢?
        // 因为是在堆上开辟空间,出了这个范围依然有效
    }
    void Test(void) {
        char* str = NULL;
        str = GetMemory();
        printf(str);
    }
    int main() {
        Test();
        return 0;
    }
    
  • void GetMemory(char** p, int num) {
        *p = (char*)malloc(num);
    }
    void Test(void) {
        char* str = NULL;
        GetMemory(&str, 100);
        strcpy(str, "hello");
        printf(str);
    }
    int main() {
        Test();
        return 0;
    }
    // 没有free
    
  • void Test(void) {
        char* str = (char*)malloc(100);
        strcpy(str, "hello");
        free(str);
        // 一定要置空
        if (str != NULL) {
            strcpy(str, "world");
            printf(str);
        }
    }
    int main() {
        Test();
        return 0;
    }