2017-05-22 33 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