0

I am making my own version of make. I allow for some arguments to be passed via command line.

I am working on it in chunks. I am setting the fileName right now

I have the following code

int main(int argc, char *argv[]) {
    char *fileName = NULL;
    char fileFlag[2];

    strcpy(fileFlag, "-f");
    printf("%s\n", fileFlag);
    if (argc == 1) {
        fileName = (char *) malloc(sizeof("Makefile"));
        strcpy(fileName, "Makefile");
        printf("One arg %s\n", fileName);
    }
    printf("\n%s", fileName);
    return 0;
}

When it runs I get the following output.

-f
One arg Makefile

Shouldn't it print another line?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
John Hamlett IV
  • 495
  • 11
  • 23
  • 3
    `fileFlag` isn't big enough to hold two chars and a nul terminator. – Riley Sep 27 '16 at 17:41
  • Sorry, was wrong about `sizeof("Makefile")`... Surprisingly it is returning the length of the string including the terminator. – Eugene Sh. Sep 27 '16 at 17:44
  • But I wonder why would the string literal be interpreted as array in this case... – Eugene Sh. Sep 27 '16 at 17:46
  • 1
    @EugeneSh. From _6.4.5 String literals_: "The multibyte character sequence is then used to initialize an **array** of static storage duration and length just sufficient to contain the sequence" and from _6.5.3.4 The sizeof and _Alignof operators_: "When applied to an operand that has array type, the result is the total number of bytes in the array." – Riley Sep 27 '16 at 17:57
  • Note that if `argc != 1`, code attempts `printf("\n%s", NULL);` – chux - Reinstate Monica Sep 27 '16 at 18:58

1 Answers1

2

The first problem is

  strcpy(fileFlag, "-f");

fileFlag is one element short of the required space, you need to have 3 element-array to store "-f" along with the terminating null. In this case, as per the strcpy() behaviour,

The strcpy function copies the string pointed to by s2 (including the terminating null character) into the array pointed to by s1. [...]

So, including the null-character, the size of the source is 3, so is needed for the destination also. Otherwise, you'll be accessing out of bound memory which invokes undefined behavior.

That said,

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261