使用for循环进行内存分配 [英] Memory allocation using for loop

查看:149
本文介绍了使用for循环进行内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的疑问仅是关于内存分配,所以不要考虑程序输出

My Doubt is regarding only memory allocation so don't think about program output

#include<stdio.h>

int main(){

  for(int i=0;i<20;i++){
     char *str=malloc(sizeof(char)*6); //assuming length of each string is 6
     scanf("%s",str);
     insertinlinkedlist(str);
  } 

} 

每当我如上图所示在此处分配内存时,只有char数组的基地址将传递到链接列表,这就是为char数组分配的内存块仅在main内部,并且我将该数组的基地址存储在 str (对于main而言是本地的),并传递给 insetinlinkedlist

whenever i allocate memory here as shown above only the base address of char array will pass to linked list,and that is the memory block allocated for char array is inside main only and i am storing the base address of that array in str which is local to main and is passed to insetinlinkedlist

我想问的是,循环内何时分配内存,为什么要分配多少内存?由于变量名相同,因此创建的内存块(未声明的char数组的数量)等于 n (循环运行的时间),因为我们应该将变量名指向相同的内存位置请注意,在循环运行内存时,我一直通过运行循环来检查编译器的值, str 的值是不同的

I want to ask whenever memory is allocated inside loop than why the number of memory blocks(no of char arrays declared ) are created equal to n (number of time loop runs) since variable name is same we should be directed to same memory location Note I have checked in compiler by running the loop all the times when loop runs memory the value of str is different

is上面的方法通过循环和相同的变量分配内存是正确的:该方法确保每次我们以上述方式分配内存时,它们不会冲突,而内存分配以及每次获取唯一地址时内存块"

is The above method is correct of allocating memory through loop and through same variable "Is the method ensures that every time we allocate memory in above manner their will be no conflicts while memory allocation and every time we will get the address of unique memory block"

现在,毫无疑问的在我心中也产生了疑问.如果我们做类似的事情

Now above doubt also creates a doubt in my mind That if we do something like that

int main(){
   for(int i=0;i<n;i++){
   array[50];


   } 
}

然后它还将在堆栈框架内创建50个数组

then it will also create 50 array inside stack frame

推荐答案

malloc返回一个指向第一个分配字节的指针.在内部,它跟踪分配了多少内存,因此知道要释放多少内存(您确实需要插入对free()的调用,否则会泄漏内存).通常,它是通过在它给您的指针之前在 之前分配一点内存并在其中存储长度来实现的,但是并不需要这样做.

malloc returns a pointer to the first allocated byte. Internally it keeps track of how much memory was allocated so it knows how much to free (you do need to insert calls to free() or you'll leak memory, by the way). Usually, it does this by allocating a little bit of memory before the pointer it gives you and storing the length there, however it isn't required to do it that way.

malloc分配的内存不以任何方式绑定到main.当前main是唯一一个其局部变量具有指向该内存的指针的函数,但是您可以将指针传递给另一个函数,并且该函数也将能够访问该内存.此外,当调用malloc的函数返回时,除非手动释放,否则该内存将保持分配状态.

The memory allocated by malloc is not tied to main in any way. Currently main is the only function whose local variables have a pointer to that memory, but you could pass the pointer to another function, and that function would also be able to access the memory. Additionally, when the function that called malloc returns, that memory will remain allocated unless manually freed.

变量名称无关紧要.指针(至第一近似值)只是一个数字.就像如何运行 int a = 42;a = 20; 允许并将a的先前值替换为新的 int * p = malloc(n);p = malloc(n); 首先将第一个malloc调用返回的指针分配给p,然后将其替换为第二个调用的返回值.您也可以有多个指向相同地址的指针:

The variable name doesn't matter. A pointer is (to first approximation) just a number. Much like how running int a = 42; a = 20; is permitted and replaces the previous value of a with a new one, int *p = malloc(n); p = malloc(n); will first assign the pointer returned by the first malloc call to p, then will replace it with the return value of the second call. You can also have multiple pointers that point to the same address:

int *a = malloc(42);
int *b = malloc(42);
int *c = a;
a = malloc(42);

在该代码的结尾,c将被设置为第一个malloc调用返回的值,而a将具有最后一个malloc调用返回的值.就像您完成了一样:

At the end of that code, c will be set to the value returned by the first malloc call, and a will have the value returned by the last malloc call. Just like if you'd done:

//assume here that f() returns a different value each time
//it's called, like malloc does
int a = f(); 
int b = f(); 
int c = a;
a = f();

关于您问题的第二部分:

As for the second part of your question:

for(int i=0;i<n;i++){
   int array[50];
} 

上面的代码将创建一个数组,该数组在当前堆栈框架内有足够的空间容纳50个整数.它对于for循环内的块而言是局部的,并且不会在迭代之间持续存在,因此不会创建n个单独的数组副本.由于以这种方式声明的数组 是本地堆栈框架的一部分,因此您无需手动释放它们;当您退出该街区时,它们将不复存在.但是您可以将指向该数组的指针传递给另一个函数,并且只要您没有退出该块,它就将是有效的.所以下面的代码...

The above code will create an array with enough space for 50 ints inside the current stack frame. It will be local to the block within the for loop, and won't persist between iterations, so it won't create n separate copies of the array. Since arrays declared this way are part of the local stack frame, you don't need to manually free them; they will cease to exist when you exit that block. But you could pass a pointer to that array to another function, and it would be valid as long as you haven't exited the block. So the following code...

int sum(int *arr, size_t n) {
   int count = 0;
   for (size_t i = 0; i < n; i++) { 
       count += arr[i];
   }
   return count;
}

for(int i=0;i<n;i++){
   int array[50];
   printf("%d\n", sum(array, 50));
}

...将是合法的(无论如何,从内存管理的角度来看;您永远不会初始化数组,因此未定义sum调用的结果).

...would be legal (from a memory-management perspective, anyway; you never initialize the array, so the result of the sum call is not defined).

作为次要说明,将 sizeof(char)定义为1.在这种情况下,您只能说 malloc(6).分配较大类型的数组时,需要 sizeof .

As a minor side note, sizeof(char) is defined to be 1. You can just say malloc(6) in this case. sizeof is necessary when allocating an array of a larger type.

这篇关于使用for循环进行内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆