程序不幸崩溃了,我不知道为什么
有人知道为什么这个程序在“ printf”上崩溃了,我不知道说实话,谢谢。 在此处输入映像描述
从注释中添加了:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char *content;
}DATABASE;
DATABASE *database;
void example(DATABASE *db){
db = malloc(sizeof(DATABASE));
db[0].content = calloc(6,1);
memcpy(db[0].content,"hello",6);
}
void main(){
example(database); //it crashes here!!!
printf("%s\n",database[0].content);
}
Does anyone know why this program crashes at "printf", I have no idea to be honest, thanks in advance.
enter image description here
Added from comments:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char *content;
}DATABASE;
DATABASE *database;
void example(DATABASE *db){
db = malloc(sizeof(DATABASE));
db[0].content = calloc(6,1);
memcpy(db[0].content,"hello",6);
}
void main(){
example(database); //it crashes here!!!
printf("%s\n",database[0].content);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是在文件作用域中声明的数据库指针被初始化为空指针。
它通过值传递给函数
example
。该函数处理数据库指针值的副本。函数内副本的更改不会反映指针本身的值。因此取消引用空指针会导致未定义的行为。您需要通过指向它的指针(指向指针的指针)间接通过引用传递指针。在函数内取消引用指针,您将可以直接访问原始指针的值。
例如,
请注意,根据 C 标准,不带参数的函数
main
应声明为The problem is that the pointer
database
declared in the file scope is initialized as a null pointer.It is passed to the function
example
by value. That is the function deals with a copy of the value of the pointerdatabase
. Changes of the copy within the function do not reflect on the value of the pointer itself. So dereferencing the null pointer results in undefined behavior.You need to pass the pointer by reference indirectly through a pointer to it (pointer to pointer). Dereferencing the pointer within the function you will get a direct access to the value of the original pointer.
For example
Pay attention to that according to the C Standard the function
main
without parameters shall be declared like呼叫
示例(数据库)
被变量数据库
是不可传统的。此变量(指针)的副本也传递给了该函数。在功能内部,此副本是初始化的,但是该副本在功能末尾的范围不超出范围。呼叫printf
进行变量数据库
具有原始的非初始化值。努力学习如何逐步调试代码。这将使您的编程更加容易。
When the call
example(database)
is made the variabledatabase
is uninitialized. Also THE COPY of this variable (which is a pointer) is passed to the function. Inside the function this COPY is initialized, but the copy goes out of scope at the end of the function. When the call toprintf
is made the variabledatabase
has the original uninitialized value.Make an effort to learn how to debug your code step by step. It will make the programming a lot easier for you.