Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy causing EXC_BAD_ACCESS?

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.

like image 932
Macro206 Avatar asked Oct 25 '25 06:10

Macro206


1 Answers

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.

like image 188
Carl Norum Avatar answered Oct 28 '25 04:10

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!