I have a function that receives by a pointer the location where will be stored. This place can have different other similar structs.The function has to read a file. This file have stored a struct, which i need to read.
typedef struct user_manage_t{
short int user_id;
char permission;
long int other_id;
long int check;
}user_manage_t;
typedef struct holder_t{
user_manage_t *user_manage;
user_manage_t *user_manage_backup;
//(...)and a lot of stuff
}holder_t;
holder_t holder;
int db_read_from_file(user_manage_t *prt){
DEBUG_PRINT("READ_FROM file started");
FILE *fd_read;
char buffer[480];
int read, bytesRead=0;
int num;
const struct user_manage_t *header;
fd_read = fopen("/home/user/user_list","r+b");
if (fd_read == NULL)
{
printf("Error");
}
else
{
DEBUG_PRINT("Its open!!!");
}
do
{
read=fread(buffer, 2, 90, fd_read);
bytesRead=bytesRead+read;
DEBUG_PRINT("Number of bytes lidos read=%d",bytesRead);
}while(read!=0); //(bytesRead < 480);
header = (struct user_manage_t *) (buffer);
fclose(fd_read);
if ( NULL == ( prt = calloc( 10, sizeof(user_manage_t))))//aloca
{
DEBUG_PRINT("MAJOR_ERROR: couldnt allocate mem to users");
return -1;
}
else
{
memcpy( (struct user_manage_t *) &prt, &buffer, 90);
DEBUG_PRINT("Users copied to main list");
for ( short int i=0;i<4 ; i++ )
{
DEBUG_PRINT("i= %hd",i);
DEBUG_PRINT("User id: %d",holder.user_manage[i].user_id );
DEBUG_PRINT("Permission: %d",holder.user_manage[i].permission);
DEBUG_PRINT("other_ID:%ld",holder.user_manage[i].other_id);
DEBUG_PRINT("Check_value:%ld", holder.user_manage[i].check);
}
return 1;
}
}
main(){
db_read_from_file((struct user_manage_t *) &holer.user_manage);
db_read_from_file((struct user_manage_t *) &holder.user_manage_backup);
}
When I run the code I get SEGFAULT and valgrind tell me this,
Thread 2:
==2746== Invalid read of size 2
==2746== at 0x80523B4: db_read_from_file (code.c:3069)
==2746== by 0x20303333: ???
==2746== Address 0x0 is not stack'd, malloc'd or (recently) free'd
This is the line of "DEBUG_PRINT("User id: %d",holder.user_manage[i].user_id );" So obviously looks like I am not storing it in the right place. Can u help me?
memcpy( (struct user_manage_t *) &prt, &buffer, 90);you copy 90 bytes to the place where theprtpointer variable is stored, not to the place where it points to. - sthmemcpyhas to be corrupting memory, unless your pointers happen to be 90 bytes in size somehow... and perhaps consider checkingprtforNULLpointers, too? - Elias Van Ootegem