简体   繁体   English

strcpy导致EXC_BAD_ACCESS?

[英]strcpy causing EXC_BAD_ACCESS?

I am making a command-line tool using Xcode 4. 我正在使用Xcode 4制作命令行工具。

I get the EXC_BAD_ACCESS error on the line with strcpy: 我在strcpy的行上得到了EXC_BAD_ACCESS错误:

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

argv[1] is -v (a "valid" option) and argv[2] is -z (an "invalid" option). argv [1]是-v(“有效”选项),argv [2]是-z(“无效”选项)。

I then need to change "invalidOption" for display reasons (printing the "error" message). 然后我需要更改“invalidOption”以显示原因(打印“错误”消息)。

Any ideas as to why this is happening? 关于为什么会发生这种情况的任何想法? Please let me know if you need any more details. 如果您需要更多详细信息,请与我们联系。

strcpy doesn't allocate any memory for you. strcpy不会为您分配任何内存。 You're trying to copy your string to NULL , which causes undefined behaviour. 您正在尝试将字符串复制到NULL ,这会导致未定义的行为。 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. 只要确保invalidOption足以容纳整个字符串(包括空终止符),否则你最终会遇到同样的问题。 You can use dynamic allocation if necessary. 如有必要,您可以使用动态分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM