为什么我的代码表现得像这样?

时间:2013-11-07 03:44:58

标签: c string pointers

这是我在这里的第一个问题所以如果它不是一个有用的问题,我道歉。

我有一个模拟器项目,用户通过命令行使用一些参数调用程序。比如,MYPROG [options] filename

我需要确保文件名有效,在哪里(目录)并获取名称以供进一步使用。

以下是代码的一部分:

char* ExtrairNome(char* alvo){
    char* teste = alvo;
    char* nome = NULL;
    int barras = 0;

    while(strcmp(teste, "") != 0){ //look for "/"
        if (teste[0] == '/') barras++;
        teste++;
    }

    teste = alvo;
    if (barras > 0){
        while(barras > 0){ //remove everything leaving the "filename.ias"
            if (teste[0] == '/') barras--;
            teste++;
        }
    }

    int i = 0;
    char aux[strlen(teste) - 4];
    while (strcmp(teste, ".ias")){ //remove the ".ias"
        aux[i] = teste[0];
        teste++;
        i++;
    }
    printf("random %d\n", barras); //this line fixes the bug!!
    aux[i] = '\0';
    nome = aux;
    return nome;
}

此函数接收具有完整文件名的字符串,并且只返回名称,不带扩展名或路径。但它只有在我返回之前打印一些变量时才有效。如果我删除该行,该函数不返回任何内容。 我认为这与范围有关,但我不确定。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

nome是一个指针,因此您可以返回解决方案的地址。 问题是辅助,它在堆栈中,一旦你返回,它就不再存在,所以行为是未知的。你有两个选择,在更高的范围内声明“aux”并将其传递给你的函数,并将指针传递给缓冲区解决方案或在函数中分配(使用malloc)然后释放(当它没有必要时)。

我的意思是:

char name[100];
ExtrairNome(alvo, name);//pass a pointer to the function

void ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     //except you don't create aux here, you use the one you created in your main function
}

char * ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     char * aux = (char*)malloc((strlen(teste)-4 )* sizeof(char));
     ...;//everything the same
}
//remember to free() when you are done using it

答案 1 :(得分:0)

您正在返回指向本地自动(堆栈)变量的指针 - aux。函数返回后不存在。这是未定义的行为。当你打印变量时它“有效”的事实是未定义行为的一种可能性。

相关问题