2017-05-22 35 views
-1

我必須創建鏈接列表。在這些列表中,我將定義指向函數的指針。我的錯誤是每當我調用該函數時,我都得到了分段錯誤錯誤。在請,下面是我的代碼誰能幫助:C:指向structre內部函數的指針會導致分段錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


typedef struct CommandStructure{ 
    char CommandName[10]; 
    char ShortKey; 
    void (* CommandAction)(void); 
} CommandFrame; 

typedef struct LinkedCommandsStructure{ 
    CommandFrame * Entity; 
    struct LinkedCommandsStructure * NextCommand; 
} Firmware_Command; 


void PrintSEQHelp(){ 
    printf("HelloPrint \n"); 
} 


CommandFrame * SEQ_Help(){ 
    CommandFrame * Entity = malloc(sizeof(Entity)); 

    strcpy(Entity->CommandName, "help"); 

    Entity->ShortKey = 'h'; 

    Entity->CommandAction = PrintSEQHelp; 

    return Entity; 
} 



Firmware_Command * SEQ_CommandsInit(){ 

    Firmware_Command * HeadOfCommands = malloc(sizeof(HeadOfCommands)); 
    Firmware_Command * HelpCommand  = malloc(sizeof(HelpCommand)); 

    HelpCommand->Entity = SEQ_Help(); 

    HelpCommand->NextCommand = NULL; 

    HeadOfCommands = HelpCommand; 

    return HeadOfCommands; 
} 


void callcommand(Firmware_Command * ActiveCommands){ 
    ActiveCommands = malloc(sizeof * ActiveCommands); 
    printf("inside callcommand \n"); 

    (ActiveCommands->Entity->CommandAction)();  

} 


int ModulesInit() { 

    int ParseRet; 

    Firmware_Command * ActiveCommands = malloc(sizeof(ActiveCommands)); 

    ActiveCommands = SEQ_CommandsInit(); 
    callcommand(ActiveCommands); 

    return 1; 
} 



void main(void){ 
    int cmdInitRet; 

    cmdInitRet = ModulesInit(); 
} 
+1

你應該做一些調試。 –

+0

絕對我做過 – moibrahim

+2

'CommandFrame * Entity = malloc(sizeof(Entity));' - >'CommandFrame * Entity = malloc(sizeof(* Entity));'和許多類似的錯誤。 – BLUEPIXY

回答

0

你做,你有一個變量,你爲它分配內存的代碼幾次,但後來與其他一些價值覆蓋它。或者分配一個以前的值。但最重要的是,在callcommand函數中,您傳入一個變量,然後用一個未初始化的內存塊重寫它的值,然後嘗試使用它。你不需要分配內存 - 傳入的變量應該是一個有效的指針了。

void callcommand(Firmware_Command * ActiveCommands){ 
    // ActiveCommands = malloc(sizeof * ActiveCommands); Not needed at all 
    printf("inside callcommand \n"); 

    (ActiveCommands->Entity->CommandAction)();  

} 
+0

感謝您的幫助 – moibrahim