关于字符串和字符的访谈问题

use*_*783 3 c string malloc free char

我遇到了一家公司的两个问题.这两个问题让我困惑.任何人都可以帮助解释答案的原因吗?

  1. 写下结果.

    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)

    答:它会输出"世界"

  2. 写下结果.

    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:输出未知,因为指针无效.

usr*_*usr 9

两者都会导致未定义的行为.

第一个是因为你str在释放它之后使用指针()(free()在块之后没有/不能将指针设置为NULL).

第二个是因为您正在使用指向另一个函数的局部变量的指针.

  • "提问者想知道为什么......即使它是UB" - 这听起来像矛盾(或者不了解UB是什么). (2认同)