[英]EXC_BAD_ACCESS when calling printf()
What's wrong with this? 这怎么了
int main(int argc, char** argv) {
printf("%% ");
size_t len;
ssize_t read;
char* line;
int size;
read = getline(&line, &len,stdin);
printf("my name: %s\n",argv[0]);
printf("%s",line);
char* args[]= {"yoyoyo","hi","me",NULL};
return 0;
}
Debugging shows Exception: EXC_BAD_ACCESS (code=1, address=0xa66647360)) on the 调试显示异常:EXC_BAD_ACCESS(代码= 1,地址= 0xa66647360)
printf("my name: %s\\n",argv[0]); printf(“我的名字:%s \\ n”,argv [0]); line.
线。
You're forgetting to initialize the values supplied to getline()
. 您忘记了初始化提供给
getline()
的值。
Try with char *line = NULL;
尝试使用
char *line = NULL;
and size_t len = 0;
并且
size_t len = 0;
instead. 代替。
The man 3 getline
man page has an example you could adapt. man 3 getline
手册页上有一个您可以改编的示例。
I suspect your problem is not with that line but with this: 我怀疑您的问题不在于那条线,而是与此有关:
read = getline(&line, &len,stdin);
line
is declared as a char *
and isn't pointed to anything. line
被声明为char *
,并且未指向任何内容。 Thus, you're reading in data to the memory location of an uninitialized pointer, which is why you're getting an access error. 因此,您正在将数据读入未初始化指针的内存位置,这就是为什么您会遇到访问错误的原因。
Try either statically allocating line: 尝试静态分配行:
char line[256]; // or whatever line length you want
read = getline(&line, &len, stdin);
or using malloc: 或使用malloc:
char *line = malloc(sizeof(char) * 256);
read = getline(line, &len, stdin);
but be careful of overflowing whatever length you set. 但请注意,无论您设置的长度是多少。 Good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.