简体   繁体   English

在C中为一维数组分配内存

[英]Allocating memory for one dimensional array in C

I have a question in regards to creating a dynamic array. 我对创建动态数组有疑问。

int *p; 
p = malloc( 3 * sizeof( int ) );

// initializes elements in the array
for ( int i = 0; i < 3; ++i ) {
    *p++ = i * 4;
}

how can i free the memory i just allocated? 如何释放刚分配的内存? for some reason, i find much easier deallocating a two dimensional array than one LOL. 由于某种原因,我发现解除二维数组的分配比一个LOL容易得多。 It's been along time since the last time i used C. 自从我上次使用C以来已经有一段时间了。

if i do the following: 如果我执行以下操作:

free( p ); // will probably get an error. 

Another thing in regards to pointers. 关于指针的另一件事。 I tried this: 我尝试了这个:

int * p = malloc( sizeof( int ) );
*p = 4;

printf( "%d\n", *p ) // prints 4 as expected

free( p );
printf( "%d\n", *p ) // still prints the number 4!!!

the free function should release the block of memory that p points to. 释放功能应释放p指向的内存块。 how is it that printf stills prints 4 then? 然后printf仍然打印4张照片?

Malloc() returns a pointer to the allocated block. Malloc()返回一个指向已分配块的指针。 Keep it for future use with free(). 使用free()保留它以备将来使用。 Index your array with integer OR walk through it with a pointer, but keep the original address stored somewhere. 用整数索引数组,或使用指针遍历数组,但将原始地址保存在某处。

You can do like this 你可以这样

int *p = malloc(3 * sizeof(int));
for( int i = 0; i < 3; i++)
   p[i] = 4*i;
// .....
free(p);

or 要么

int *p = malloc(3 * sizeof(int));
int *q = p;
for( int i = 0; i < 3; i++)
   *q++ = 4*i;
// .....
free(p);

In the first case, you just write free(p) as you only allocated one block of memory. 在第一种情况下,您只写了free(p)因为您只分配了一块内存。

What you are doing in the second case is undefined behaviour. 在第二种情况下,您正在做的事情是不确定的行为。 It might print 4, it might crash, it could do literally anything. 它可能会打印4,可能会崩溃,它实际上可以执行任何操作。 The chances are that the implementation is just marking that location as reusable, but not actually clearing it out (why should it, it's a waste of time) 可能是该实现只是将该位置标记为可重用,但实际上并未清除该位置(为什么要浪费时间)

free(p) de allocates memory pointed by p . free(p) de分配p指向的内存。 But p still having memory address which is de allocated by free(p) . 但是p仍然具有由free(p)分配的内存地址。 De-allocation means that block of memory added to list of free memories which is maintained by memory allocation module. 取消分配是指将内存块添加到空闲内存列表中,由内存分配模块维护。 When you print data pointed by p still prints value at address because that memory is added to free list and not removed. 当您打印由p指向的数据时,仍会在地址处打印值,因为该内存已添加到空闲列表中而不被删除。

  1. how can i free the memory i just allocated? 如何释放刚分配的内存?

    You could do something like this 你可以做这样的事情

     int *p; p = malloc( 3 * sizeof( int ) ); // initializes elements in the array for ( int i = 0; i < 3; ++i ) { p[i] = i * 4; } 

    this would not change p , so you could use free(p) to free it. 这不会更改p ,因此您可以使用free(p)释放它。

    If you need to change p , you should remember its original value in another variable, and call free() on that original value, such as 如果需要更改p ,则应记住其在另一个变量中的原始值,并对该原始值调用free() ,例如

     int *op; op = p; /* do something that changes `p` */ free(op); 
  2. how is it that printf stills prints 4 printf静止图像如何打印4

    What you did, access a dynamically allocated memory region after you freed it, will lead to undefined behavior. 在释放动态访问的内存区域后,所做的操作将导致未定义的行为。 It could print 4 , it also could crash or do something really wild. 它可能会打印4 ,也可能崩溃或执行某些真正荒唐的事情。

how can i free the memory i just allocated? 如何释放刚分配的内存?

When we want to free a memory chunk previously allocated by malloc() , we use the free function. 当我们想要释放先前由malloc()分配的内存块时,我们使用free函数。 This function accepts a char pointer to a previously allocated memory chunk, and frees it - that is, adds it to the list of free memory chunks, that may be re-allocated. 此函数接受指向先前分配的内存块的char指针,并释放它-即,将其添加到可能重新分配的空闲内存块列表中。 Use free(p) . 使用free(p)

how is it that printf stills prints 4 then? 然后printf仍然打印4张照片?

Usage Of free() : free()用法

Several notes about free() : 关于free()几点说明:

  • The size of the chunk was stored by malloc() previously in its memory map, and that is how free() knows how many bytes to free. 块的大小先前由malloc()存储在其内存映射中,这就是free()如何知道要释放多少字节的方式。
  • The freed memory is not being cleared or erased in any manner. 释放的内存不会以任何方式清除或擦除。 This is why accessing memory that was just freed often does not cause a crash - any data in it is still the same as before calling free() . 这就是为什么访问刚刚释放的内存通常不会导致崩溃的原因-内存中的任何数据仍然与调用free()之前的数据相同
  • The free() function cannot nullify pointers to the given memory chunk that might still exist in our program. free()函数不能使指向仍可能存在于我们程序中的给定内存块的指针无效。 After we call free() , it is up to us (the programmers) not to try and dereference pointers that still point to that memory chunk . 在调用free() ,我们(程序员)应该决定不要尝试取消对仍然指向该内存块的指针的引用 Such pointers are known as 'dangling pointers' - they point to memory that was already freed, and thus they should NOT be dereferenced again, unless they are assigned the address of a different (not-freed) memory chunk. 这样的指针称为“悬挂指针”-它们指向已经释放的内存,因此,除非为其分配了不同(未释放)内存块的地址,否则它们不应再次被取消引用。

In first case you can still free the memory by taking the pointer back to the first element's address and then calling free(p) like: 在第一种情况下,您仍然可以通过将指针移回第一个元素的地址,然后调用free(p)来释放内存,如下所示:

p = p-3;
free(p);

Reason : malloc store some information about how much memory need to be freed once allocated dynamically that's why you need to point it back to the start so that free can read that information and free exactly 3 int memory allocated by malloc. 原因 :malloc存储一些有关动态分配后需要释放多少内存的信息,这就是为什么您需要将其指向起点,以便free可以读取该信息并准确释放malloc分配的3个int内存。

In your second case it is still printing is not universal result, output can be anything even program may crash. 在第二种情况下,仍然打印不是通用结果,即使程序可能崩溃,输出也可以是任何东西。

Reason : free do not do anything special with the memory it only add it back to the FREE LIST it maintains for the memory available for dynamic allocation. 原因 :free对内存不做任何特殊处理,它仅将其添加回它维护的FREE LIST中,以供动态分配的内存使用。 It is only up-to the programmer that they do not dereference the after calling free on it. 完全由程序员决定,他们在对free调用之后不取消引用。

Malloc ==> Only allocate the memory (not changing memory data to NULL ) Malloc ==>仅分配内存(不将内存数据更改为NULL)

Free ==> Only It will release the allocated resources on the pointer,(not changing memory data to NULL ) Free ==> Only它将释放指针上分配的资源(不将内存数据更改为NULL)

In both cases user has the responsibly to set appropriate value if required. 在这两种情况下,用户都可以根据需要负责地设置适当的值。

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

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