简体   繁体   English

内存分配和char数组

[英]Memory allocation and char arrays

I still do not quite understand, what exactly will happen in the situation: 我还是不太明白,情况究竟会发生什么:

int i = 0;
for(i; i <100; i ++)
{
    char some_array[24];
     //...
    strcpy(some_array,"abcdefg");

}

Will the some_array act as: some_array会表现为:

some_array = malloc(24);

At the beginning of the cycle and free(some_array) at the end of the cycle? 在循环开始时和循环结束时的free(some_array)

Or those variables are gonna be allocated in the stack, and after the function ends destroyed? 或者那些变量将在堆栈中分配,并在函数结束后被销毁?

some_array is local to the block , so it's created at the beginning of each iteration of the loop, and destroyed again at the end of each iteration of the loop. some_array块的本地,因此它在循环的每次迭代开始时创建,并在循环的每次迭代结束时再次销毁。

In the case of a simple array, "create" and "destroy" don't mean much. 在简单数组的情况下,“创建”和“破坏”并不意味着什么。 If (in C++) you replace it with (for example) an object that prints something out when it's created and destroyed, you'll see those side effects happen though. 如果(在C ++中)用(例如)一个在创建和销毁时打印出某些东西的对象替换它,你会发现这些副作用会发生。

There are two ways of storing character strings. 有两种存储字符串的方法。 1. Creating some space using malloc and then storing the char string In this case memory is allocated from heap and will not be freed until you free it explicitly. 1.使用malloc创建一些空间然后存储char字符串在这种情况下,内存是从堆中分配的,在显式释放之前不会释放内存。 Here memory is not deallocated even after the scope 2. Creating an array and storing in it Here memory is allocated from stack and is freed implicitly after the scope 这里内存即使在范围2之后也没有被释放。创建一个数组并存储在其中这里内存是从堆栈中分配的,并且在范围之后隐式释放

There is no implicit malloc() or free calls introduced by the example shown. 显示的示例没有隐式的malloc()或免费调用。

You can demonstrate that by adding a "free(some_array)" statement within the loop body. 您可以通过在循环体中添加“free(some_array)”语句来证明这一点。 The result will be a compilation error. 结果将是编译错误。

The array is - as far as the program is concerned - created at the start of the block and destroyed at the end. 就程序而言,数组是在块的开头创建的,并在结束时被销毁。 Which means the C programmer must assume it is created and destroyed for every iteration of the loop. 这意味着C程序员必须假设它是为循环的每次迭代创建和销毁的。

It is up to the compiler as to whether the array is created on the stack - or how it optimises the repeated creation and destruction of the array. 编译器是否在堆栈上创建数组 - 或者它如何优化重复创建和销毁数组。 In practice, it often will be created on the stack. 实际上,它通常会在堆栈上创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM