I have a question to ask, which occurred when reading the concept of static variables. If I create an allocated block of memory in a function, using malloc
, and then the function returns to main
, without having used free()
on the allocated memory, will that memory block be susceptible to changes in the course of the program, or not? I mean, after I leave the function is it possible that the memory block can be overwritten by another process, while I wanted to use it and/or edit it in my way, or is it "locked" from something like that, until I free it? Is it possible for the block to be considered as free of data before I free it?
5 に答える
malloc
特定のバイト数を編集すると、明示的に指定しない限り、プログラムの存続期間を通じて存続しますfree
。
どの関数で実行したかは関係ありません。edメモリmalloc
への有効なポインタがあれば、プログラム内のどこでも使用できるようにメモリが有効になりmalloc
ます。
The C Standard specifies a storage duration called allocated (in C99 6.2.4 Storage duration of objects.) The lifetime of allocated storage is from allocation (with malloc, calloc, realloc) until deallocated (with free or realloc). So, yes, returning from a function does not invalidate allocated storage (unlike automatic storage like local variables). You can expect it to be still allocated. And you can read and write it as long as you have a valid pointer to such storage.
通常、2 つのプロセスは 2 つの異なる仮想アドレス空間に存在するため、malloc されたメモリ ブロックを別のプロセスで上書きすることはできません。
メモリが malloc で割り当てられると、プログラムが実行されている限り、このメモリ ブロックを解放しない限り、メモリはプログラムに割り当てられたままになります。したがって、このメモリ ブロックは、別のプロセスによって変更または上書きできません。
わかりました、では、このような状況で何が起こるかを尋ねていると思います...
#include <stdlib.h>
void myfunc( void )
{
static void* p = malloc(BLOCK_SIZE);
// perhaps the rest of this function uses the pointer to the allocated mem...
}
int main( int argc, char** argv )
{
myfunc();
// the rest of the program goes here...
}
...そして、「残りのプログラム」コードが によって割り当てられたメモリブロックに書き込むことができるかどうかを尋ねますmyfunc()
。
myfunc()
コードだけがメモリ ブロックへのポインタを保持していることがわからないため、ヒープにはまだメモリが割り当てられています。ただし、「ロック」することもありません (つまり、書き込みから保護します。C 言語自体にはそのような概念はありません)。
ヒープがまだメモリ ブロックを既に割り当てられていると見なしているため、後続を使用したコードは、既に割り当てmalloc()
たブロック内にあるブロックへのポインタを取得しません。また、外部のコードmyfunc()
はポインターの値を認識しませんp
。したがって、後のコードがブロックに書き込む唯一の方法は、ブロック内のメモリ内にたまたまあった場所へのポインターを何らかの方法で取得して (おそらく何らかのコードのバグが原因で)、「偶然に」書き込みを行うことです。それ。