Error when using a structure with an array of chars in C -


i have struct contains array of chars , struct has struct. passed reference function initializes array. then, call function print , free array.

please me, wrong program?

#include <stdio.h> #include <stdlib.h>  typedef struct {   char *x;   double y; } a;  typedef struct {   a;   int w; } b;  void f(b *b) {   int i;    b->w = 5;   b->a.x = (char *) malloc(sizeof(char) * 5);   printf("addres in f %p: \n", b->a.x);    for(i = 0; < 5; i++)     b->a.x[i] = 'a';    b->a.y = 20; }  void p(b *b) {   int i;    printf("w: %d\n", b->w);   printf("addres in p %p: \n", b->a.x);   printf("x: %s\n", b->a.x);   printf("y: %f\n", b->a.y);   free(b->a.x); }  int main(int argc, char **argv) {   b b;    f(&b);   p(&b);    return 0; } 

when run valgrind, occurs following:

==28053== error summary: 1 errors 1 contexts (suppressed: 6 2) ==28053==  ==28053== 1 errors in context 1 of 1: ==28053== invalid read of size 1 ==28053==    @ 0x3a03e489d7: vfprintf (in /lib64/libc-2.10.1.so) ==28053==    0x3a03e4fb49: printf (in /lib64/libc-2.10.1.so) ==28053==    0x400633: p (test_struct.c:33) ==28053==    0x400686: main (test_struct.c:43) ==28053==  address 0x4c20035 0 bytes after block of size 5 alloc'd ==28053==    @ 0x4a0763e: malloc (vg_replace_malloc.c:207) ==28053==    0x400574: f (test_struct.c:19) ==28053==    0x40067a: main (test_struct.c:42) 

and output:

addres in f 0x16b4010:  w: 5 addres in p 0x16b4010:  x: aaaaa y: 20.000000 

thanks, hg

you haven't null-terminated 'string' b->a.x printf("x: %s\n", b->a.x); reads past end of allocated memory causes error getting in valgrind.

you can fix changing

b->a.x = (char *) malloc(sizeof(char) * 5);   printf("addres in f %p: \n", b->a.x);    for(i = 0; < 5; i++)     b->a.x[i] = 'a'; 

to

b->a.x = malloc(6 * sizeof b->a.x); printf("address in f %p: \n", b->a.x);  for(i = 0; < 5; i++)     b->a.x[i] = 'a'; b->a.x[i] = '\0'; 

here i've increased size of dynamically allocated block of memory 6 , i've explicitly null-terminated 'string' b->a.x[i] = '\0';. \0 used null-terminate strings in c.


note: pointed out @michi in comments. in c there no need cast result of malloc().

i've rewritten sizeof(char) sizeof b->a.x better portability in case change type of b->a.x.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -