I've got 2 functions, func1()
and func2()
. func2
takes a character array as input. Both functions run on different threads. I call func2
from func1
. When I passed a stack allocated array to func2
, I got garbage values when I printed the array from inside func2()
. However, when I passed a heap allocated array to func2
, I got the correct string inside func2()
i.e.
func2(char * char_array)
{
/* Some code */
cout<<char_array;
}
/* This does not work(Garbage values were printed in func2()) */
func1()
{
char array_of_char[SIZE];
memset(array_of_char,0,SIZE);
strncpy(array_of_char,"SOME_STRING",SIZE);
func2(array_of_char); //Asynchronous call to func2(). func1() proceeds immediately.
/*
some code
*/
}
/* This works(Correct values were printed in func2) */
func1()
{
char * array_of_char=new char[SIZE];
memset(array_of_char,0,SIZE);
strncpy(array_of_char,"SOME_STRING",SIZE);
func2(array_of_char); //Asynchronous call to func2(). func1() proceeds immediately.
/*
some code
*/
}
Does this mean that in multi-threaded programs, whenever some pointer has to be passed between different threads, the pointer should always be pointing at a heap-allocated memory?
Please note that func2() is actually a callback function which executes on the occurrence of an event. I've hidden those details in the question. Func1() does not stop/wait for the execution of func2().
Edit: I feel like I need to provide some more details of my implementation. In my program, I'm using Datastax C++ client library for Cassandra. Please find the link in the end, containing some details of the functions used in the program:
int main()
{
func1();
/* some code */
return 0;
}
/* This does not work(Garbage is printed in func2) */
void func1()
{
/* some code */
char array_of_char[SIZE];
memset(array_of_char,0,SIZE);
strncpy(array_of_char,"SOME_STRING",SIZE);
CassFuture* l_query_future = NULL;
/* some code where query is created */
l_query_future = cass_session_execute(rtGetSession(), l_stmt); //l_stmt is the query statement, rtgetSession() returns CassSession *
cass_future_set_callback ( l_query_future, func2, (void *)array_of_char); //details in the link given in the end
/* some code */
}
/* This works(Correct values were printed in func2) */
void func1()
{
/* some code */
char * array_of_char=new char[SIZE];
memset(array_of_char,0,SIZE);
strncpy(array_of_char,"SOME_STRING",SIZE);
CassFuture* l_query_future = NULL;
/* some code where query is created */
l_query_future = cass_session_execute(rtGetSession(), l_stmt); //l_stmt is the query statement, rtgetSession() returns CassSession *
cass_future_set_callback ( l_query_future, func2, (void *)array_of_char);
/*
some code
*/
}
void func2(CassFuture* l_query_future, void * data)
{
/* some code */
cout<<(char *)data;
}
References for Datastax driver APIs: