2011-07-24 13 views
0

この質問は無効です!私は適切に学生を解放していませんでした!私はこれを私に許されているように素早く私に明らかにした答えを受け入れるでしょう!strlenとmalloc:Cメモリリーク

私はCを新しくmallocを練習しています。壮大な範囲で、私はリンクリストライブラリを書いています。このcreate_student関数は、リンクリストライブラリをテストするために使用する多くの関数の1つです。問題は...私はvalgrindを実行してこの関数を呼び出し、最初のmallocによって引き起こされたいくつかのメモリリークがあることを示します。それはすべて最高の私の知識に、固体になります:valgrindのから

typedef struct Student 
{ 
     char* first_name; /* This will be malloc'd!*/ 
    char* last_name; /* This will also be malloc'd */ 
    int grade; 
    long id; 
} Student; 


Student* create_student(const char* first_name, const char* last_name, int grade, long gtid) 
{ 

     /* First allocate a student on the heap */ 
     Student *newStudentp = (malloc(sizeof(Student))); 


    /* Allocate enough space for the first and last names */ 
    newStudentp -> last_name = (malloc(strlen(last_name))); 
    newStudentp -> first_name = (malloc(strlen(first_name))); 



     // AND copy the first and last name to the first and last name fields in the struct 
    strncpy(newStudentp -> first_name, first_name, strlen(first_name)); 
    strncpy(newStudentp -> last_name, last_name, strlen(last_name)); 



     /* Set the grade and id */ 
    newStudentp -> grade = grade; 
    newStudentp -> id = id; 

     */ 
    return newStudentp; 
} 

私のエラーメッセージが(いくつかがある)のようになります。

==4285== 9 bytes in 1 blocks are definitely lost in loss record 8 of 8 
==4285== at 0x4025BD3: malloc (vg_replace_malloc.c:236) 
==4285== by 0x804855B: create_student (test.c:24) 
==4285== by 0x8048748: main (test.c:109) 

ライン24は

newStudentp -> last_name = (malloc(strlen(last_name))); 

ラインであります。

エラーの原因となっているstrlenの基本的な誤用がありますか?

+2

あなたのStudent構造体はどのように無料ですか? – Mat

+2

'strlen'は' \\ '文字を含む文字列_not_の長さを返します。 – Hasturkun

+1

'last_name'の' malloc'は '\ 0 'のスペースを入れるために' strlen(last_name)+ 1'文字を割り当てるべきです( 'first_name'と同じです) – jonsca

答えて

1

はここにいくつかの問題があります。

newStudentp -> last_name = (malloc(strlen(last_name))); 
    newStudentp -> first_name = (malloc(strlen(first_name))); 

strlenだけでなく、終端'\0'を含めないように長さを断念します。しかし、それも格納する必要がありますので、どちらの場合でもstrlen(last_name) + 1を使用してください。

また、strncpy()は、ソース文字列ではなく、割り当てられたバッファのサイズを使用することをお勧めします。しかし、既にmalloc(strlen(...) + 1)を使用しているので、ここでstrcpy()をそのまま使用することができます。

+1

strncpy()はまれに正しい関数です。他のstrn *()関数とは異なり、strcpy()の "より安全な"バージョンではありません。場合によっては、ターゲット配列を非終端記号にしておくことができます(つまり、有効な文字列ではありません)。他のものでは、追加の '\ 0'文字でターゲットをパディングする時間を無駄にすることがあります。 –