Access Violation Error while trying to make a memory allocation - c

struct DynamicArray {
int allocated;
int used;
int *array;
}; typedef struct DynamicArray DynamicArray;
DynamicArray * ArrayCreate(int initialSize) {
DynamicArray *array;
(*array).array = (int*)malloc(initialSize*sizeof(int)); //Debugger points this line.
if((*array).array == NULL) {
return NULL;
}
(*array).allocated = initialSize;
(*array).used=0;
return array;
}
I am trying to make my own library for dynamic arrays. Just to learn and improve myself. Please review my code. What am I doing wrong?

You are de-referencing an uninitialized pointer here:
DynamicArray *array; // uninitialized
(*array).array = .... // ooops
You need to make array point to some memory you can write to. For example
DynamicArray *array = malloc(sizeof(DynamicArray));

First use this :
DynamicArray *array;
array = (DynamicArray *)malloc(sizeof(struct DynamicArray));
array->array = ...
If you don't initialize a point you can't dereference it because its point to NULL.

Related

How do allocate dynamic memory for a array inside a structure in C and How to access it

How to access the array elements after allocate the memory.
I cont able to allocate a memory inside a structure how do perform that:
How do allocate dynamic memory for a array inside a structure in C and How to access it
#include<stdio.h>
#include<stdlib.h>
struct student{
int *arr = (int*) malloc(10 * sizeof(int));
int reg;
};
void main()
{
struct student *ptr = (struct student*) malloc(sizeof(struct student));
ptr->reg = 10;
ptr->arr[0] = 100;
printf("register no : %d\n",ptr->reg);
printf("register no : %d\n",ptr->arr[0]);
return ;
}
You can't give a default value for struct members.
Once you have an instance of struct student, then you can allocate memory to the arr member.
#include <stdio.h>
#include <stdlib.h>
struct student{
int *arr;
int reg;
};
int main()
{
struct student *ptr = malloc(sizeof(struct student));
ptr->reg = 10;
ptr->arr = malloc(10 * sizeof(int))
ptr->arr[0] = 100;
printf("register no : %d\n",ptr->reg);
printf("register no : %d\n",ptr->arr[0]);
return 0;
}
One common pattern is to create a function that does the allocation and freeing of the struct (error handling not included) for you:
#include <stdlib.h> // malloc(), free()
struct student {
int *arr;
int reg;
};
// ...
struct student *student_allocate(int reg_n) {
struct student *student = malloc(sizeof(* student));
student->arr = malloc(sizeof(int) * reg_n);
student->reg = reg_n;
return student;
}
void student_free(struct student *student) {
free(student->arr);
free(student);
}
// ...
int main() {
struct student *student = student_allocate(10);
// do something with student
student_free(student);
}
In addition to #dbush's answer, you can also reorder your struct to make the pointer as a 1-sized array in the last field and allocate the whole stuff at once:
struct student {
int reg; // First fields are the general info
// any other fixed-size fields
int arr[1]; // LAST field is the array
};
Then,sizeof(struct student) is the size of the "general info" plus the size of an int, so you can allocate whatever amount of bytes for arr in one call to malloc() and arr points to whatever memory you allocated:
int nreg = 10;
struct student *pt = malloc(sizeof(struct student) + (nreg - 1) * sizeof(int));
pt->reg = nreg;
pt->arr[3] = 12; // pt->arr is the array you allocated with nreg*sizeof(int)
In the structure, we may only have a pointer to the array we want to store in memory or a pointer to an array of a fixed size (For example: int arr[10];) The array will have to be dynamically allocated later if we choose the first option.
We cannot give structure members default values or handle allocation of memory in the structure itself. I believe this is what you're looking for:
#include<stdio.h>
#include<stdlib.h>
struct student {
int *arr;
int reg;
};
void main()
{
struct student *ptr = (struct student*) malloc(sizeof(struct student));
ptr->reg = 10;
ptr->arr = (int*) malloc(10 * sizeof(int));
ptr->arr[0] = 100;
printf("register no : %d\n",ptr->reg);
printf("register no : %d\n",ptr->arr[0]);
return;
}

C Heap Allocating a Hard Coded Struct Array

I am having trouble figuring out how to make a hard-coded array heap allocated.
Imagine I have the structures:
struct my_struct
{
...
};
struct holder
{
my_struct *array_of_struct;
...
};
Now to create an instance of struct holder though, the array of struct my_struct has to be hard-coded, such as:
struct holder *new_holder()
{
struct holder *my_holder = malloc(sizeof(struct holder));
if (my_holder == NULL)
exit(-1);
struct my_struct arr[] = {mystruct_instace_1, mystruct_instance_2, ...};
holder->array_of_struct = arr;
return holder;
}
This assignment though wont work, because its pointing to arr which is stack allocated. How would I go about making this assignment of holder->array_of_struct heap allocated?
The super-lazy way to do it is just copy the array into a buffer from malloc(), as follows:
struct my_struct arr[] = {mystruct_instace_1, mystruct_instance_2, ...};
holder->array_of_struct = malloc(sizeof(arr));
assert(holder->array_of_struct);
memcpy(holder->array_of_struct, arr, sizeof(arr));
return holder;
By "super-lazy" I mean "minimum number of lines of code written".

Memory corruption cause by free()

I'm trying to understand how does dynamic memory allocation in C work. So I coded this:
typedef struct person{
int id;
int credit;
}person_t;
typedef struct list{
int id;
person_t * people;
}list_t;
int main(){
list_t * list;
list = malloc(sizeof(list_t));
list->people = malloc(10 * sizeof(person_t)); //list for 10 people
free(list->people);
free(list);
}
, which appears to be correct. However, when I decided to create functions for allocation\deallocation, double free or corruption error started to appear:
void init_list(list_t * listptr, int size){
listptr = malloc(sizeof(list_t));
listptr->people = malloc(size * sizeof(person_t));
}
void clear_list(list_t * listptr){
free(listptr->people);
free(listptr);
}
int main(){
list_t list;
init_list(&list, 10); //list for 10 people
clear_list(&list);
}
Output:
Error in ./list: double free or corruption (out) : 0x00007ffc1b3fba70
Why could that be? Thanks in advance.
void init_list(list_t * listptr, int size){
listptr = malloc(sizeof(list_t));
listptr->people = malloc(size * sizeof(person_t));
}
is not correct. You are modifying listptr in the function. That does not change anything of list in main. You need to remove the line fhat changes listptr in that function. Use:
// listptr is already a valid pointer.
// There is no need to allocate memory for it.
void init_list(list_t * listptr, int size){
listptr->people = malloc(size * sizeof(person_t));
}
You have a worse mistake in clear_list.
void clear_list(list_t * listptr){
free(listptr->people);
free(listptr);
}
You are calling free on a pointer that was not allocated by a call to malloc. listptr is a pointer to the object that was created in stack in main. Remove the second call to free. Use:
// listptr is a pointer to an object on the stack in main.
// Trying to call free on it is an error.
void clear_list(list_t * listptr){
free(listptr->people);
}

Dynamic allocation of structs in C

I have a problem with dynamic memory allocation. Here is the code so please help.
#include <stdio.h>
int i;
typedef struct{
int A;
}node;
typedef struct Model
{
node *m;
} Model;
Model M;
void initialize(Model *a, int size)
{
a->m = (node*) malloc(size);
}
void model_init(Model *a, int len)
{
int i;
for (i=0;i<len;i++) a->m[i].A = 20;
}
int main()
{
initialize(&M ,10);
model_init(&M, 10);
for (i=0;i<10;i++) printf("%d\n",M.m[i].A);
}
I am trying to make a Model that has 10 nodes and I want to assign values to nodes in variable A. The printf shows (-1819044973, -1819044973, 14128019, 3969, 0, 0, 0 ...)
I just want it to say for example M.m[2].A=20
What am I doing wrong? please help.
TY
void initialize(Model *a, int size)
{
a->m = (node*) malloc(sizeof(node) *size); // NOTICE HERE!!!!
}
Your initialize function allocates a number of bytes then model_init later assumes that many node instances will be available. node is larger than 1 byte (at least sizeof(int) bytes) so you write beyond the end of allocated memory.
The easiest fix is to change initialize:
void initialize(Model *a, int elements)
{
a->m = malloc(elements * sizeof(node));
}
For more information on the fact that you don't have to cast malloc :
Do I cast the result of malloc?

How to malloc "MyDef ** t" to a specific length, instead of "MyDef * t[5]" in C

A struct like the following works fine, I can use t after calling malloc(sizeof(mystruct)):
struct mystruct {
MyDef *t[5];
};
I want to be able to dynamically set the length of the array of MyDef, like the following:
struct mystruct {
MyDef **t;
int size;
};
What do I need to do additionally to malloc(sizeof(mystruct)) to get this to work, so I can do TestStruct->t[3] = something? Just getting a segmentation fault!
Thanks!
EDIT with code that causes seg fault, unless I'm blind this seems to be what the answers are so far:
#include <stdio.h>
typedef struct mydef {
int t;
int y;
int k;
} MyDef;
typedef struct mystruct {
MyDef **t;
int size;
} MyStruct;
int main(){
MyStruct *m;
if (m = (MyStruct *)malloc(sizeof(MyStruct)) == NULL)
return 0;
m->size = 11; //seg fault
if (m->t = malloc(m->size * sizeof(*m->t)) == NULL)
return 0;
return 0;
}
struct mystruct *s = malloc(sizeof(*s));
s->size = 5;
s->t = malloc(sizeof(*s->t) * s->size);
m = (MyStruct*)malloc(sizeof(MyStruct)) == NULL
What that does. Calls malloc, compares return of malloc to NULL. Then assigns the result of that comparison(a boolean value) to m.
The reason it does that is because '==' has a higher precedence than '='.
What you want:
if ( (m = (MyStruct *)malloc(sizeof(MyStruct))) == NULL)
...
if ( (m->t = malloc(m->size * sizeof(*m->t))) == NULL)
That happens because you do not allocate memory for array itself, only for pointer to this array.
So, first you have to allocate mystruct:
struct_instance = malloc(sizeof(mystruct));
and then you have to allocate memory for array of pointers to MyDef and initialize pointer in your struct
struct_instance->size = 123;
struct_instance->t = malloc(sizeof(MyDef*) * struct_instance->size);

Resources