Why does setting a breakpoint make my code work?

2019-07-28 01:14发布

问题:

I'm very new to C so I'm sure I am doing loads wrong however this is puzzling me.

My code should get a title from the user and create a folder in the route directory with that name. It only works if I set a breakpoint on the makeFolder() implementation. For some reason that small rest before I click continue makes it work (I'm using Xcode).

By doesn't work I mean it returns 0 correctly but no folder is created.

This is one of my first attempts at doing anything with C and I'm just messing around trying to learn it.

Edit Many thanks for your answers and comments. It is now working as expected and I learned a little along the way. You are all scholars and gentlemen.

#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:

The malloc'd variable path contains garbage, because you never explicity fill it. Running this code in debugger may cause that it accidently sees zeroed out memory which then accidently give the expected results.

You should at least set the first character of path to initial zero like that:

path[0] = '\0';

Otherwise concat() cannot work properly.