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);
}
CodePudding user response:
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 pointer database
. 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
void example(DATABASE **db){
*db = malloc(sizeof(DATABASE));
( *db )->content = calloc(6,1);
memcpy( ( *db )->content,"hello",6);
}
//...
example( &database );
Pay attention to that according to the C Standard the function main
without parameters shall be declared like
int main( void )
CodePudding user response:
When the call example(database)
is made the variable database
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 to printf
is made the variable database
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.