Search code examples
cstructvalgrindmemcpy

Invalid read of size 1 when accessing a member of a struct


I've been running into this same issue for a few days now and have managed some workarounds but I need to understand where I am going wrong.

This is the valgrind error which causes a segmentation fault and crash

==14609== Invalid read of size 1
==14609==    at 0x4E80F90: vfprintf (vfprintf.c:1655)
==14609==    by 0x4E87F56: fprintf (fprintf.c:32)
==14609==    by 0x4017ED: display_tickets (tm_options.c:261)
==14609==    by 0x400E5D: main (tm.c:83)
==14609==  Address 0xa is not stack'd, malloc'd or (recently) free'd

The code I'm trying to run is fairly simple.

void display_tickets(tm_type *tm) {

struct stock_data data;
struct stock_node *current;
memcpy(&data, tm->stock->head_stock->data, sizeof(tm->stock->head_stock->data));

  printf("%s", data.ticket_name);  /*THIS WORKS, name is as expected*/
  fprintf(stdout, "Name is %s", 40, data.ticket_name); /*this causes the read error*/

}

ticket_name is just a string (size 40), which is a member of "struct stock_data".

Can anyone shed some light it's doing my head in....


Solution

  • On the line:

    fprintf(stdout, "Name is %s", 40, data.ticket_name);
    

    Your specify the format %s, which expects the next unused argument to be a string, but you are passing an int (40). Remove the 40, and it should work. (Or did you mean the format to be %*s?)