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

pun*_*lly 1 c debugging malloc xcode

我很新,C所以我确定我做错了但是这让我很困惑.

我的代码应从用户处获取标题,并在路径目录中使用该名称创建一个文件夹.它只适用于我在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;
}
Run Code Online (Sandbox Code Playgroud)

cod*_*nix 6

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

您应该至少将第一个字符设置path为初始零,如下所示:

path[0] = '\0';
Run Code Online (Sandbox Code Playgroud)

否则concat()无法正常工作.