Mik*_*ike 3 c xcode command-line exc-bad-access
我正在使用XCode在C中创建命令行程序.在运行程序时,它最初会执行它应该执行的操作(询问我的文件路径).但是,当我键入有效的和现有的文件路径时,它会给我以下错误:
Program received signal: “EXC_BAD_ACCESS”. sharedlibrary apply-load-rules all (gdb)
Run Code Online (Sandbox Code Playgroud)
我的程序中有两个警告,这两个警告都与strcat函数有关.警告是:
warning: implicit declaration of function 'strcat'
Run Code Online (Sandbox Code Playgroud)
和
warning: incompatible implicit declaration of built-in function 'strcat'
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我的程序没有正常执行.
谢谢,迈克
我的代码发布在下面:
#include "stdlib.h"
int main (void)
{
char *string1;
printf("Type in your file path: ");
scanf("%s", string1);
char *string2 = "tar czvf YourNewFile.tar.gz ";
strcat(string2, string1);
system(string2);
}
Run Code Online (Sandbox Code Playgroud)
也许它与分配字符有关?
你忘了分配空间string1,scanf不会为你分配内存,你必须自己做.此外,string2指向不可写入的内存并且它没有足够的空间可以附加string1到它,所以strcat即使你有,你也会溢出char string2[] = "tar czvf YourNewFile.tar.gz ";.
这是一个注释版本的东西,更接近你真正想要的东西:
#include <stdio.h> /* printf, sprintf, fgets */
#include <string.h> /* strcat, strlen */
#include <stdlib.h> /* malloc */
#define TAR "tar czvf YourNewFile.tar.gz"
int main(void) {
char path[100] = { 0 }; /* Initialize to all 0 bytes. */
char *cmd; /* We'll allocate space for this later. */
int len;
printf("Type in your file path: ");
fgets(path, sizeof(path), stdin); /* Read at most 100 characters into path */
/*
* Remove the trailing newline (if present).
*/
len = strlen(path);
if(path[len - 1] == '\n')
path[len - 1] = '\0';
/*
* Allocate room for our command.
*/
cmd = malloc(
strlen(TAR) /* Room for the base tar command. */
+ 1 /* One more for the space. */
+ strlen(path) /* Room for the path we read. */
+ 1 /* One more for the final nul terminator. */
);
/*
* You could also use a bunch of strcpy and strcat stuff for
* this but sprintf is less noisy and safe as long as you've
* properly allocated your memory.
*/
sprintf(cmd, "%s %s", TAR, path);
/*
* This is vulnerable to unpleasant things in `path` (such as spaces,
* &, >, <, ...) but this will do as a learning exercise. In real life
* you'd probably want to use fork and exec for this to avoid the
* interface issues with the shell.
*/
system(cmd);
/*
* Free the memory we allocated.
*/
free(cmd);
/*
* You need a return value because of "int main(...)". Zero is
* the standard "all's well" return value.
*/
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我犯了任何一个错误的错误,请有人告诉我.
您可以在此处找到上述功能的参考资料.
检查这一行:
char *string1
Run Code Online (Sandbox Code Playgroud)
这一行:
scanf("%s", string1);
Run Code Online (Sandbox Code Playgroud)
你没有为string1声明一个大小,这意味着你总会得到一个错误,修复它是这样的:
char string1[100]
如果100是输入的最大长度.
或者按字符阅读输入字符.
并且,要摆脱警告,请添加#include "string.h"到您的#include陈述所在的位置.