-1

consider the struct

typedef struct{
    int a;
    char b;
    float c;
    const int *ptr;
}check;

in the main function

static check *p= NULL;
p = (check *)malloc(sizeof(check));
memset(p,0,sizeof(check));

now i give values to some members [ thats why i memset to 0 so that all members are init]

int num = 10;
p->a = 1;
memcpy(p->ptr,&num,sizeof(int));

Result: Segmentation fault

Question: how do give value present at "num" and pass it to the ptr?

MURICA213
  • 17
  • 2
  • 2
    At no point in your code do you assign a value to `p->ptr` so it's an invalid pointer. You cannot `memcpy` into it – UnholySheep Jul 01 '22 at 11:03
  • ptr is not initialized. It is pointing to an undefined address. In other words, there is no allocated object at the address pointed to by ptr. – Itagaki Fumihiko Jul 01 '22 at 11:04
  • `const`doesn't really makes sense for what you are trying to do. You want `int *ptr`. – alex01011 Jul 01 '22 at 11:08
  • `memcpy` is not what is needed to copy _the address_ of `num`: `p->ptr = &num` solves that. – Computable Jul 01 '22 at 11:25
  • NULL may not be a zero bit pattern on your architecture and compiler. The `memset` leaves `p` in an implementation defined state. This might become relevant again in the near future with ARM64 having tagged pointers. – Goswin von Brederlow Jul 01 '22 at 13:05

1 Answers1

0

You need to allocate the actual storage for the integer (malloc), and make your pointer modifiable (remove const).

The line memset(p,0,sizeof(check)); clears all fields of the check structure, including the pointer ptr.

Remove the const qualifier or you won't be able to modify ptr.

int num = 10;
p->a = 1;
p->ptr = malloc(sizeof(int));     // This line allocates memory to save an int
memcpy(p->ptr,&num,sizeof(int));
mmixLinus
  • 1,646
  • 2
  • 11
  • 16
  • 1
    @Gardener Thats just wrong. `memcpy` copies `n` bytes from `src` to `dst`. `sizeof(int)` yields the size of an int in bytes. – alex01011 Jul 01 '22 at 11:18
  • @Gardener Nowadays plain **ints** are mostly 32-bits not 64, so that will be 4 bytes compared to the 8 of the pointer. Good luck! – alex01011 Jul 01 '22 at 11:21
  • @Gardener I don't know where you get your info. Probably an outdated text book? The [manpage](https://linux.die.net/man/3/memcpy) agrees with me, and so does the [glibc implementation](https://github.com/lattera/glibc/blob/master/sysdeps/i386/memcopy.h) of `memcpy`. – alex01011 Jul 01 '22 at 11:30