简体   繁体   English

为什么在尝试比较两个字符串时会出现分段错误?

[英]Why do I get segmentation fault on trying to compare two strings?

I was working on an assignment for a simple assembler that should recognize arbitrary variable names like high programming languages.我正在为一个简单的汇编程序进行分配,该汇编程序应该可以识别任意变量名称,例如高级编程语言。 I tried to use Dynamic allocation to an array of char pointers我尝试对 char 指针数组使用动态分配

I am just trying to make an extensible array of strings and being able to search this array for specific strings But it gives a segmentation fault on the line of trying to compare the two strings [line: 14]我只是想创建一个可扩展的字符串数组并能够在这个数组中搜索特定的字符串但是它在尝试比较两个字符串的行上给出了分段错误[行:14]

Comp(&buffer[1], Variables[i];
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define Comp(a,b)  strcmp(a,b) == 0 ? 1 : 0

char buffer[255], **Variables;
int VariableIndex;

void A_instructionHandler() {
    int A_Operand, test = 0;
    if (buffer[0]== '@') { 
        for (int i = 0; i <= VariableIndex; i++) {
            test = Comp(&buffer[1], Variables[i]);
            if (test) { 
                A_Operand = i + 16; 
                break;
            }   
        }   
    }   
}

int main(int argumentCounter, char *arguments[]) { 
    strcpy(buffer, "@variable");
    Variables = (char **)calloc(VariableIndex + 1, sizeof(char**));
        A_instructionHandler();
}

Here's that code refactored into something more idiomatic:这是重构为更惯用的代码:

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

void instruction_handler(char* buffer, char** variables) {
  switch (buffer[0]) {
    case '@':
      // This iterates over the NULL terminated array by stopping when
      // it hits a NULL pointer, or in other words *v is false.
      for (char **v = variables; *v; ++v) {
        // If this matches a variable name...
        if (!strcmp(*v, &buffer[1])) {
          // Variable matched, so show some debugging code
          printf("Found variable: %s\n", *v);
          return;
        }
      }
  }
}

int main(int argc, char* argv[] ) {
  // Create a simple NULL-terminated array of arbitrary size
  char *variables[] = {
    "variable",
    NULL
  };

  instruction_handler("@variable", variables);
}

Where that variables array can be defined however you like, extended, shrunk, so long as the NULL terminator remains in place at the end.只要 NULL 终止符在最后保持原位,就可以根据需要定义variables数组的位置、扩展、缩小。

Some tips based on your original code:基于您的原始代码的一些提示:

  • Don't use global variables unless you have an extremely compelling reason.除非您有非常令人信服的理由,否则不要使用全局变量。 No such reason existed here.这里不存在这样的理由。
  • Make your functions clear in intent and purpose.使您的职能在意图和目的上明确。
  • Pick a naming convention and stick to it.选择一个命名约定并坚持下去。
  • Use C conventions like strcmp() and just deal with how weird it is, don't wrap that in a #define and invent your own C dialect nobody understands.使用诸如strcmp()之类的 C 约定并处理它有多奇怪,不要将其包装在#define中并发明自己的 C 方言,没人能理解。 You'll get used to C over time, it won't bother you as much, and you can code without driving other people on your team up the wall.随着时间的推移,您会习惯 C,它不会给您带来太多困扰,而且您可以编写代码,而无需让团队中的其他人陷入困境。
  • Explanations like argc expanded to argumentCounter is better expressed as a comment than an awkwardly long variable name, especially one that's very non-standard.argc扩展为argumentCounter的解释比一个笨拙的长变量名更好地表示为注释,尤其是一个非常非标准的变量名。 Comments are great.评论很棒。 Use them as much as you like!尽可能多地使用它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM