Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为什么在块中分配的数组在块结束后仍然存在?_C - Fatal编程技术网

C 为什么在块中分配的数组在块结束后仍然存在?

C 为什么在块中分配的数组在块结束后仍然存在?,c,C,一旦函数退出,本地数组的内存就会被释放,对吗?那么,当我使用块来代替时,为什么会起作用呢 int main(int argc, char **argv){ char *s2; { char s[] = "testing"; s2 = s; } printf("%s\n", s2); return 0; } 这取决于执行情况。唯一确定的是,s不能保证保持可访问性,但当然也可以 只是未定义的行为。因此,不要依赖它。它实际上

一旦函数退出,本地数组的内存就会被释放,对吗?那么,当我使用块来代替时,为什么会起作用呢

int main(int argc, char **argv){
    char *s2;

    {
        char s[] = "testing";
        s2 = s;
    }

    printf("%s\n", s2);
    return 0;
}

这取决于执行情况。唯一确定的是,
s
不能保证保持可访问性,但当然也可以


只是未定义的行为。因此,不要依赖它。

它实际上并不存在。该printf的结果未定义。它似乎按预期工作,因为您的特定编译器没有保护您不这样做,并且该内存的内容没有在其他应用程序中设置和更改


数组s[]的内容不再有效,即使是s2指针也无法使用。

释放内存块并不意味着写入的内容被擦除/清除。实际上,您的程序调用未定义的行为。
对于新手和有经验的程序员来说,访问以前释放的内存块是导致许多内存错误的原因。

当内存“空闲”时,它只意味着可以再次使用。存储在那里的任何数据都将保留,直到该部分内存再次使用为止。但是如果你要编写更复杂的代码,调用一些函数,传递一些变量,分配一些变量。。您将看到此内存被重用

这是在用C编写代码时必须考虑的一个常见问题。例如,假设您正在编写一个返回字符串值的函数。。您需要一些空间来存储在函数退出后仍然有效的字符串。您不能将其作为函数(或块,如您在问题中所做的)中的局部变量分配,因为该内存仅在函数期间属于您

例如:

那么,我们怎么写这个呢?一个常见的解决方案是:

char *func1(char *s, int len) {
  mydata = "here is the data";

  /* copy the data into the provided memory.. but if it is too short, */
  /* make sure the string is null terminated                          */
  strncpy(s, mydata, len);
  s[len-1] = 0;    

  return s;
}

int main(int argc, char**argv) {
  /* allocate at least as much memory as we will need */
  char mymem[100];

  /* pass pointer to mymem into func1, and tell func1 how much space it has */
  char *s = func1(mymem, sizeof(mymem));
}

有道理吗?您也可以使用malloc()和free(),但这对于这个问题来说太多了…

很幸运-不要依赖它,尽管
s
无效且超出范围({..})。因此,引用该地址的
s2
也是无效的(UB)。可能重复的不仅仅是“不要依赖”它,而是一个完全错误。
char *func1(char *s, int len) {
  mydata = "here is the data";

  /* copy the data into the provided memory.. but if it is too short, */
  /* make sure the string is null terminated                          */
  strncpy(s, mydata, len);
  s[len-1] = 0;    

  return s;
}

int main(int argc, char**argv) {
  /* allocate at least as much memory as we will need */
  char mymem[100];

  /* pass pointer to mymem into func1, and tell func1 how much space it has */
  char *s = func1(mymem, sizeof(mymem));
}