Copying char arr[64] to char arr[] can cause a segmentation fault?
Copying char arr[64] to char arr can cause a segmentation fault?
typedef struct {
int num;
char arr[64];
} A;
typedef struct {
int num;
char arr;
} B;
I declared A* a;
and then put some data into it. Now I want to cast it to a B*
.
A* a;
B*
A* a;
a->num = 1;
strcpy(a->arr, "Hi");
B* b = (B*)a;
Is this right?
I get a segmentation fault sometimes (not always), and I wonder if this could be the cause of the problem.
I got a segmentation fault even though I didn't try to access to char arr
after casting.
char arr
1 Answer
1
This defines a pointer variable
A* a;
There is nothing it is cleanly pointing to, the pointer is non-initialised.
This accesses whatever it is pointing to
a->num = 1;
strcpy(a->arr, "Hi");
Without allocating anything to the pointer beforehand (by e.g. using malloc()
) this is asking for segfaults as one possible consequence of the undefined behaviour it invokes.
malloc()
...asking for undefined behaviour
@SouravGhosh While you are correct, it is not asking for UB, it is. Isn't it?
– Yunnosch
3 mins ago
@SouravGhosh Not guaranteed, sometimes what you ask for you do not get. ;-)
– Yunnosch
1 min ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Maybe, better,
...asking for undefined behaviour
? segmentation fault is not guaranteed, you know.– Sourav Ghosh
5 mins ago