重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

ListInsert,ListDeleteに問題があると思うのですが、その問題に気づけません。アドバイス、間違いの指摘等していただければと思います。よろしくお願いします。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<crtdbg.h>
/* リストセル定義 */
typedef struct cell{
char *string;
struct cell *next;
}CELL,*PCELL;
/*リストヘッダ作成 */
PCELL ListCreate(){
return calloc(1,sizeof(CELL));
}
/*
headerで指定されたリストからstrで指定された文字列を
格納したセルを検索し,その直前のセルを指すポインタを返す
*/
PCELL ListGetPrevPos(PCELL header,const char *str){
while (header->next){
if (strcmp(header->next->string,str)==0){
return header;
}
header=header->next;
}
return NULL;
}
/*
PCELL pos:特定のセルを指すポインタ
戻り値:posの次のセルのポインタ
*/
PCELL ListNext(PCELL pos){
return pos->next;
}
/* リスト表示 */
void ListPrintAll(PCELL header){
puts("- addr -- next -:string");
printf("[%08x][%08x]:HEADER\n", header, header->next);
header=header->next;
while(header){
printf("[%08x][%08x]:<%s>\n",header,header->next,header->string);
header=header->next;
}
puts("------");
}
/* 新しいセルを挿入する */
PCELL ListInsert(PCELL pos, const char *string){
PCELL pNewCell;
pNewCell=calloc(1,sizeof(CELL));
if(pNewCell!=NULL){
pNewCell->string=malloc(strlen(string)+1);
strcpy(pNewCell->string,string);
pNewCell->next=pos->next;
pos->next=pNewCell;
}
return pNewCell;
}
/* セルの削除 */
void ListDelete(PCELL pos){
struct cell *ptemp1;
char *ptemp2;
ptemp2=calloc(1,sizeof(pos->next->string));
ptemp1=pos->next;
ptemp2=pos->next->string;
pos->next=pos->next->next;
free(ptemp2);
free(ptemp1);
}
/* リスト全体の削除 */
void ListDestroy(PCELL header){
while(header->next!=NULL){
ListDelete(header);
}
free(header);
}

int main(){
PCELL header;
header=ListCreate();
ListInsert(header,"grape");
ListInsert(header,"apple");
ListInsert(header,"kiwi");
ListPrintAll(header);
ListInsert(ListNext(ListGetPrevPos(header,"apple")),"banana");
ListDelete(ListGetPrevPos(header,"apple"));
ListDelete(header);
ListPrintAll(header);
ListDestroy(header);
_CrtDumpMemoryLeaks();//メモリリークの表示
}

A 回答 (2件)

うん, ListDelete でリークしてる. ?alloc と free の数が合わない. そもそも ListDelete において ptemp2 の意味がまったくない.


ちなみにこの calloc の使い方は危ない. メンバ next が NULL になることを期待しているんだろうけど, それは (規格では) 保証されていない.

この回答への補足

理解が不十分な状態であるため、どの部分のfreeがまだ行われていないのかが分かりません。よろしければお教えいただけないでしょうか?

補足日時:2010/12/03 19:27
    • good
    • 0
この回答へのお礼

何とか自己解決できました。ご指摘して頂きありがとうございました。

お礼日時:2010/12/03 20:08

PCELL ListInsert(PCELL pos, const char *string){


PCELL pNewCell;
pNewCell=calloc(1,sizeof(CELL));
if(pNewCell!=NULL){
このelseでpNewCell=calloc(1,sizeof(CELL));が宙ぶらりん

この回答への補足

ご指摘ありがとうございます。

補足日時:2010/12/03 19:28
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!