结构指针奇怪的行为

时间:2019-02-16 01:12:17

标签: c pointers debugging linked-list gdb

我正在尝试使用双向链接列表制作BrainFuck(BF)解释器。但是,我浏览此列表的方式似乎对单元格产生了相当奇怪的影响。

所以首先这是我程序的一部分,让我很难过

NSString * methodName   = [NSString stringWithUTF8String:sel_getName(method_getName(method))];

char retTyp[10];

method_getReturnType(method, retTyp, 10);
const char * desiredRetType = "B";

if([methodName hasPrefix:@"func"] &&
   (0 == strncmp(retTyp, desiredRetType, strlen(desiredRetType))) &&
   (2 == method_getNumberOfArguments(method)))
{
    SEL testMethod = method_getName(method);
    return [self performSelector:testMethod];
}

Cell结构的定义如下:

int main(int argc, char **argv)
{
    Cell c = {NULL, NULL, '\0', NULL};
    Cell* codeCell = &c;
    Cell b = {NULL, NULL, '\0', NULL};
    Cell* bandCell = &b;

    //init
    bandCell->val = '\0';
    bandCell->firstCell = bandCell;

    codeCell->firstCell = codeCell;

    //get code
    printf("BF code : ");
    codeCell->val=getchar();
    while(codeCell->val != '\n') {
        if(
            codeCell->val=='<'||codeCell->val=='>'
            ||codeCell->val=='+'||codeCell->val=='-'
            ||codeCell->val=='['||codeCell->val==']'
            ||codeCell->val==','||codeCell->val=='.'
        ) {
            newCell(codeCell)->val = getchar();
            codeCell = codeCell->nextCell;
        }
        else {
            codeCell->val = getchar();
        }
    }
}

函数typedef struct Cell Cell; struct Cell { Cell* precCell; Cell* nextCell; char val; Cell* firstCell; }; 如下:

Cell* newCell(Cell*)

在这种情况下,我尝试仅按正确的BF指令逐个获取用户输入的char并将其放入单元格中。 我最终有了一个Cell* newCell (Cell* precCell) { Cell n = {precCell, NULL, '\0', precCell->firstCell}; Cell* newCell = &n; precCell->nextCell = newCell; return newCell; } ,所以我试图找到它的来源,并且我认为它来自第42行的奇怪行为:当我尝试用任何内容更新新创建的单元格的SEGFAULT时在val缓冲区中,单元格getchar()释放了所有值,但我确定它是同一单元格,因为地址仍然相同。在下面的示例中,您可以从GDB中看到我刚才所说的测试。

codeCell->nextCell

我希望这是足够的信息来理解我的问题, 预先感谢您的帮助。

0 个答案:

没有答案
相关问题