代码之家  ›  专栏  ›  技术社区  ›  punkrockbuddyholly

为什么设置断点会使我的代码工作?

  •  1
  • punkrockbuddyholly  · 技术社区  · 14 年前

    我是新来的 C

    我的代码应该从用户那里得到一个标题,并用这个名称在route目录中创建一个文件夹。只有在 makeFolder() 实施。不知为什么在我点击之前 continue 使其工作(我正在使用Xcode)。

    不起作用 我的意思是它正确地返回0,但是没有创建文件夹。

    这是我第一次尝试做任何事情 C类 我只是在胡乱学。

    编辑 非常感谢你的回答和评论。现在一切如期而至,我一路上也学到了一些东西。你们都是学者和绅士。

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <string.h>
    
    #define MAX_TITLE_SIZE 256
    
    void setTitle(char* title) {
        char *name = malloc (MAX_TITLE_SIZE);
        printf("What is the title? ");
        fgets(name, MAX_TITLE_SIZE, stdin);
    
        // Remove trailing newline, if there
        if(name[strlen(name) - 1] == '\n')
            name[strlen(name) - 1] = '\0';
    
        strcpy(title, name);
        free(name);
    }
    
    // If I set a breakpoint here it works
    void makeFolder(char * parent, char * name) {
        char *path = malloc (MAX_TITLE_SIZE);
    
        if(parent[0] != '/')
            strcat(path, "/");
    
        strcat(path, parent);
        strcat(path, "/");
        //strcat(path, name);
        //strcat(path, "/");
        printf("The path is %s\n", path);
        mkdir(path, 0777);
        free(path);
    }
    
    int main (int argc, const char * argv[]) {
        char title[MAX_TITLE_SIZE];
        setTitle(title);
        printf("The title is \'%s\'", title);
        makeFolder(title, "Drafts");
        return 0;
    }
    
    1 回复  |  直到 14 年前
        1
  •  6
  •   codymanix    14 年前

    malloc的变量路径包含垃圾,因为您从未明确地填充它。在调试器中运行此代码可能会导致它意外地看到内存归零,然后意外地给出预期的结果。

    你至少应该设置 path 从零开始:

    path[0] = '\0';
    

    否则 concat() 不能正常工作。