C找到替换不起作用

时间:2014-03-12 01:27:13

标签: c strstr

以下是无效的功能:

char * insert_symtab(char *buf)
{
  char *ret = (char *)malloc(strlen(buf) + 512);
  char *tmp = NULL;
  char *repl = NULL;
  char obuf[32]; //for converting int to hex
  Symtab_struct *cursym;
  lineQueue *lq = readlines(buf);
  int i;
  strcpy(ret, "");
  while (!lq->empty())
  {
    tmp = getlinefromqueue(lq);
    for (i = 0; (cursym = symtab->findNodeByNumber(i)) != NULL; i++)
    {
        sprintf(obuf, "0x%04x", cursym->sym_location);
        //printf("-->looking for %s\n", cursym->sym_name);
        if ((repl = strstr(tmp, cursym->sym_name)) != NULL)
        {
            printf("---->Found %s\n", cursym->sym_name);
            strncpy (repl, obuf, strlen(cursym->sym_name));
        }
    }
    strcat(ret, tmp);
    strcat(ret, "\n");
  }
  return ret;
}

当像这样运行时,我得到以下输出:

[WARN process_includes] Cannot find file included 1test2.asm
[DEBUG build_symtab] Inserting symbol  to location 0x0000
[DEBUG build_symtab] Inserting symbol $start to location 0x0008
[DEBUG build_symtab] Inserting symbol $eight to location 0x0008
[WARN in Symtab::insertNode] Redefinition of symbol $start is ignored
;include '1test2.asm'
:start:
mov a b
add a b
:eight:
:start:
sub a b
$start

而且,如果我进去改变

if ((repl = strstr(tmp, cursym->sym_name)) != NULL)
to
if ((repl = strstr(tmp, "$start")) != NULL)

我得到以下输出:

[WARN process_includes] Cannot find file included 1test2.asm
[DEBUG build_symtab] Inserting symbol  to location 0x0000
[DEBUG build_symtab] Inserting symbol $start to location 0x0008
[DEBUG build_symtab] Inserting symbol $eight to location 0x0008
[WARN in Symtab::insertNode] Redefinition of symbol $start is ignored
---->Found $start
;include '1test2.asm'
:start:
mov a b
add a b
:eight:
:start:
sub a b
0x0000

应该如此。附件是整个项目的pastebin链接:

main.cpp:http://pastebin.com/AiDCbsCt

Symtab.h:http://pastebin.com/Kmcn6NzV

Symtab.cpp:http://pastebin.com/mxtPL1d2

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

找到并纠正了问题

            for (i = 1; i < 28 && tmp[i] != ':'; i++); //i now points to the next colon
            strncpy(sym_name_tmp, tmp + 1, i - 1); //grab the symbol

需要改为

            for (i = 1; i < 28 && tmp[i] != ':'; i++); //i now points to the next colon
            strncpy(sym_name_tmp, tmp + 1, i); //grab the symbol
            *strstr(sym_name_tmp, ":") = 0; //this fixes teh 0x7f issue