Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top