The following code gives a segmentation fault. I am not able to figure out as to why. Please see..
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **ptr;
int *val;
int x = 7;
val = &x;
*ptr = (int *)malloc(10 * sizeof (*val));
*ptr[0] = *val;
printf("%d\n", *ptr[0] );
return 0;
}
on debugging with gdb, it says:
Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at temp.c:10
*ptr = (int *)malloc(10 * sizeof (*val));
Any help regarding the matter is appreciated.
To create a variable that will point to a dynamically allocated array, declare it as a pointer to the element type. For example, int* a = NULL; // pointer to an int, intiallly to nothing. A dynamically allocated array is declared as a pointer, and must not use the fixed array size declaration.
In addition to dynamically allocating single values, we can also dynamically allocate arrays of variables. Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime.
Dynamic memory allocation is to allocate memory at “run time”. Dynamically allocated memory must be referred to by pointers. the computer memory which can be accessed by the identifier (the name of the variable).
int **ptr;
*ptr = (int *)malloc(10 * sizeof (*val));
First statement declares a double pointer.
Second dereferences the pointer. In order that you are able to dereference it the pointer should point to some valid memory. it does not hence the seg fault.
If you need to allocate enough memory for array of pointers you need:
ptr = malloc(sizeof(int *) * 10);
Now ptr
points to a memory big enough to hold 10
pointers to int
.
Each of the array elements which itself is a pointer can now be accessed using ptr[i]
where,
i < 10
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int **ptr;
int x;
x = 5;
ptr = malloc(sizeof(int *) * 10);
ptr[0] = &x;
/* etc */
printf("%d\n", *ptr[0]);
free(ptr);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With