Why do I have a core dump ?

Q

QQ

I can sense that I get wrong with char *name,
however, how to fix it ?

Thanks a lot!
int Roamer_Create(const char *dbname)
{
char *name;
printf("dbname is %s\n",dbname);
sprintf(name,"CREATE DATABASE %s",dbname);
printf("command is %s\n",name);
return 1;
}


main()
{
Roamer_Create("Roamer");
}
 
J

Jens.Toerring

QQ said:
I can sense that I get wrong with char *name,
however, how to fix it ?
int Roamer_Create(const char *dbname)
{
char *name;

Now you have a pointer that points to some random place in memory.
If you're lucky it points to a place that you have no permissions
to access.
printf("dbname is %s\n",dbname);
sprintf(name,"CREATE DATABASE %s",dbname);

Now you try to write to that random place in memory. You're lucky
that the program crashed instead of blissfully overwriting some
important data of your program, making it look like everything is
ok before crashing horribly (and unexplainably) half an hour later...

To get rid of the problem you need to make 'name' point to some
memory you own, large enough to hold the string you want to put
there (including the the terminating '\0' character.

You could do use e.g.

if ( ( name = malloc( strlen( "CREATE DATABASE " ) +
strlen( dbname ) + 1 ) ) == NULL ) {
fprintf( stderr, "Running out of memory!\n" );
exit( EXIT_FAILURE );
}

before you call sprintf(). Don't forget to include <stdlib.h>, it's
needed for both the definition of malloc() and the define for the
macro EXIT_FAILURE.
printf("command is %s\n",name);
return 1;
}

This should be

int main( void )

since main() is always supposed to return an int and unless you declare
it to do so you'll get into trouble with C99 compilers.
{
Roamer_Create("Roamer");
}

And since main() must return an int you also should have a return
statement at the end.
Regards, Jens
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top