4

I am making a command-line tool using Xcode 4.

I get the EXC_BAD_ACCESS error on the line with strcpy:

char *invalidOption = NULL;
strcpy(invalidOption, argv[2]);

argv[1] is -v (a "valid" option) and argv[2] is -z (an "invalid" option).

I then need to change "invalidOption" for display reasons (printing the "error" message).

Any ideas as to why this is happening? Please let me know if you need any more details.

Macro206
  • 2,143
  • 3
  • 19
  • 25

1 Answers1

5

strcpy doesn't allocate any memory for you. You're trying to copy your string to NULL, which causes undefined behaviour. You need something like:

char invalidOption[10];
strcpy(invalidOption, argv[2]);

Just make sure that invalidOption is big enough to hold the whole string (including null terminator) or you'll end up with the same problem. You can use dynamic allocation if necessary.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • Note that the above will reserve the memory on the stack. If you need it to survive longer, you'll want to allocate a proper chunk of memory. Frankly, I'd just use `NSString` from the start. – bbum Jul 29 '12 at 20:36