gpt4 book ai didi

c - 程序收到信号 : “EXC_BAD_ACCESS” ?

转载 作者:太空狗 更新时间:2023-10-29 15:51:19 24 4
gpt4 key购买 nike

我正在使用 XCode 在 C 中制作一个命令行程序。运行该程序时,它最初会执行它应该执行的操作(向我询问文件路径)。但是,当我输入有效且现有的文件路径时,它会出现以下错误:

Program received signal:  “EXC_BAD_ACCESS”. sharedlibrary apply-load-rules all (gdb)

我的程序中有两个警告,都与函数 strcat 有关。警告是:

warning: implicit declaration of function 'strcat'

warning: incompatible implicit declaration of built-in function 'strcat'

我想知道为什么我的程序不能正常执行。

谢谢,迈克

我的代码贴在下面:

#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);
}

也许这与分配字符有关?

最佳答案

你忘记为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;
}

如果我犯了任何差一错误,请有人告诉我。

您可以在上面的over here中找到函数的引用资料.

关于c - 程序收到信号 : “EXC_BAD_ACCESS” ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6085298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com