I have a c++ library linked to main.c.
There is a global variables used in between the two files.
The variables are declared in sharedata.h
#ifndef __SHARE_DATA_H__
#define __SHARE_DATA_H__
#include <stdio.h>
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
// declare your two vars in the header file as extern.
extern pthread_mutex_t mutex;
extern int *ptr;
#ifdef __cplusplus
}
#endif
#endif /* __SHARE_DATA_H__ */
Inside main.c
, I have declaration and memallocation of ptr
. And I can read and print of data in *ptr
.
main.c
#include "sharedata.h"
pthread_mutex_t mutex;
int *ptr;
int main(){
pthread_mutex_lock( &mutex );
ptr = (int *)malloc((4 * 5) * sizeof(int));
pthread_mutex_unlock( &mutex );
/*do some other things
%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
*/
pthread_mutex_lock( &mutex );
for (int x = 0; x < 5; x++)
{
printf("%d ", *(ptr+x));
}
printf("\n");
pthread_mutex_unlock( &mutex );
}
Inside gstdsexample.cpp
, I have declaration and initialization of global variables.
But when I try to write data to *ptr, I have segmentation fault
at this line *(ptr+x) = 1;
What could be wrong?
#include "sharedata.h"
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int *ptr;
{
printf("before lock\n");
pthread_mutex_lock( &mutex );
for (int x = 0; x < 5; x++)
{
printf("before pointer\n");
*(ptr+x) = 1;
}
pthread_mutex_unlock( &mutex );
}