15

次のプログラムを見ていますが、メモリがどのように割り当てられているのか、またその理由がわかりません。

void function() {
    char text1[] = "SomeText";
    const char* text2 = "Some Text";
    char *text = (char*) malloc(strlen("Some Text") + 1 );
}

上記のコードでは、最後のコードは明らかにヒープにあります。ただし、私が理解text2しているように、プログラムのデータセグメントにありtext1、スタック上にある可能性があります。それとも私の仮定が間違っていますか?ここで正しい仮定は何ですか?このコンパイラは依存していますか?

4

2 に答える 2

18
// Array allocated on the stack and initialized with "SomeText" string.
// It has automatic storage duration. You shouldn't care about freeing memory.
char text1[] = "SomeText"; 

// Pointer to the constant string "Some Text".
// It has static storage duration. You shouldn't care about freeing memory.
// Note that it should be "a pointer to const".
// In this case you'll be protected from accidential changing of 
// the constant data (changing constant object leads to UB).
const char* text2 = "Some Text";

// malloc will allocate memory on the heap. 
// It has dynamic storage duration. 
// You should call "free" in the end to avoid memory leak.
char *text = (char*) malloc(strlen("Some Text") + 1 );
于 2011-06-01T17:07:29.993 に答える
5

はい、ほとんどのシステムで正しいです:

text1スタック上の書き込み可能な変数配列になります (書き込み可能な配列である必要があります)

text2実際にはconst char*そうである必要があり、はい、実行可能ファイルのテキストセグメントを指します(ただし、実行形式によって異なる場合があります)

textヒープになります

于 2011-06-01T17:08:09.177 に答える