我用C编写了一个电话簿程序(带有动态结构等)。
它在 Linux 下完美运行,但是当我尝试在 Windows 中运行它(在 devc++ 中编译后)时,它启动正常,但在我向列表中添加一些数据后,它就停止并退出。 只有在电话簿中添加新数据才会发生这种情况。当我使用其他功能时,没有中断等等都可以。
在模块的开头,我为 getch()
和 systen("附加了
。也许我使用了一些 Windows 中不允许的功能或类似的东西。windows.h
和 conio.h
cls”)
这是我的第一个c项目,平时都是在linux下工作,所以我应该注意什么?
/*SCREEN*/
#ifdef __WIN32__ /*for Windows*/
#include<windows.h>
#define GETCH printf("press ENTER...\n");getch()
#define CLEAR system("cls")
#endif
#ifdef __unix__ /*for unix*/
#include<unistd.h>
#define GETCH printf("\n\npress ENTER...");getchar()
#define CLEAR system("clear")
#endif
我也以同样的方式添加姓名和 pnonenumber
printf("++ ADD DATA: ++\n");
/*LASTNAME*/
printf(">> add lastname : ");
fgets(buf,128,stdin);
lastname = malloc(strlen(buf)); /*allocate memory for lastdane*/
if( lastname != NULL) /*successful allocation*/
{
strcpy( lastname, buf ); /*copy data from buf to lastname variable*/
lastname[strlen(lastname)-1]='\0';/*get the number of elements and add '\0' at the end*/
}
else /*allocation failed*/
{
printf("Memory Allocation Error!");
}
memset(buf,0,128);
<小时/>
void AddDATAsorted( char* lastname, char* firstname, char* telnumber )
{
tDATA* pDATA;
if( pTELBOOK )
{
pDATA = malloc( sizeof( tDATA )); /*allocate memory for new item*/
pDATA->lastname = lastname;
pDATA->firstname = firstname;
pDATA->telnumber = telnumber;
addItemToList( pTELBOOK, pDATA, fcmp ); /*add a new item sorted - see list.c*/
}
} /*END 6*/
它在另一个模块中。
<小时/>int fcmp( void* pItemList, void* pItemNew )
{
tDATA* pDATA_list;
tDATA* pDATA_new;
int diff;
if( pItemList != NULL )
{
pDATA_list = ( tDATA* ) pItemList; /*because void-pointer */
pDATA_new = ( tDATA* ) pItemNew;
diff = strcmp( pDATA_list->lastname, pDATA_new->lastname );
if( diff != 0 ) return diff;
else /*if items have the same lastname*/
{
diff = strcmp( pDATA_list->firstname, pDATA_new->firstname );
if( diff != 0 ) return diff;
else /*if items have also the same firstname*/
{
diff = strcmp( pDATA_list->telnumber, pDATA_new->telnumber );
if( diff != 0 ) return diff;
else return FAIL; /*if items - equal*/
}
}
}
else return OK;
调试器总是显示这里有问题......
/* 2 * 功能:删除数据*/
int RemoveDATA( void )
{
tDATA* pDATA = NULL;
if( pTELBOOK == NULL ) return FAIL;
else /*if pTELBOOK's current element - not empty - free allocated memory*/
{
if( pTELBOOK->pCurr != NULL )
{
pDATA = pTELBOOK->pCurr->pItem;
free( pDATA->lastname );
free( pDATA->firstname );
free( pDATA->telnumber );
free( pTELBOOK->pCurr->pItem );
RemoveItem( pTELBOOK ); /*and remove element from the list*/
return OK;
}
}
} /*END 2*/
最佳答案
lastname = malloc(strlen(buf)); /* problem */
if( lastname != NULL)
{
strcpy( lastname, buf);
lastname[strlen(lastname)-1]='\0';
}
使用strdup。姓氏的长度比需要的短一。这可能是一个问题:
lastname = strdup(buf);
此外,您不应该使用 128 或其他名称。使用 sizeof buf
或 sizeof (buf)
代替,或者可能是一个定义:
#define BUF_SIZE 128
我还没有检查其余的。
关于C 程序 - 在 Linux 上运行; Windows 运行时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16170746/