How to divide memory on the heap? [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Let's say I allocate a large block of memory on the heap. To make it simple lets say its 512 bytes. How would I go about dividing that 512 bytes of memory into 16 blocks of 32 bytes each?

Dynamic memory is returned as void*. Arithmetic on void* is not defined by the standard but you can cast to char* when calculating the individual block address. Like:
#define BLOCKS 16
#define BLOCK_SIZE 32
int main(void)
{
void * m = malloc(BLOCKS * BLOCK_SIZE);
assert(m != NULL);
void * dm[BLOCKS];
for (int i = 0; i < BLOCKS; ++i) dm[i] = (char*)m + i * BLOCK_SIZE;
// Use the individual blocks, e.g. print their values
for (int i = 1; i < BLOCKS; ++i) printf("%p \n", dm[i]);
free(m);
return 0;
}
Notice: The BLOCK_SIZE must take care of alignment requirements for your system.

Related

Resize Array, if it is too small for user input without string.h [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
How can I expand the array, once it is too small for the user input? For example, if char array[25] can only have 25 elements, but my sentence is 100 character long.
Is there way to do it without string.h library?
I am very new to this language and have problems with understanding dynamic allocation. And I cant find the solution in internet without using string.h
To do this, you'll need to manage your own memory allocation (in C++, std::vector makes this a lot easier). This is a very basic example of an expanding array of integers...
/* how many array elements are we using? */
int len = 0;
/* maximum capacity for the array - may change if we exceed the capacity */
int capacity = 128;
/* dynamic arrays are a pointer, with some memory allocation */
int* array = (int*)malloc(capacity * sizeof(int));
/* an example loop */
for(int i = 0; i < 256; ++i) {
/* if we are at capacity */
if(len == capacity) {
/* reallocate the array to be twice the size */
capacity = capacity * 2;
array = (char*)realloc(array, capacity * sizeof(int));
}
/* add new item into array */
array[len++] = i;
}
/* make sure we free the memory eventually to avoid a memory leak... */
if(array) free(array);

How can you dynamically allocate a pointer in the form int (*p)[n] in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Suppose I get input from somewhere and store it in a variable. Pretend the variable is Cols.
I want to make an array in the form
int (*p)[Cols]
Now, I know you can't do this. So how would I dynamically allocate it to do it?
Teaching me how to do so would really be appreciated!
You can absolutely use int (*p)[Cols], it's a pointer to array of size Cols (Cols times size of int, in bytes), you just have to allocate memory for it, until you do, it doesn't point to a valid memory location. The constraint is that the allocated memory needs to be in blocks of multiples of Cols:
int (*p)[Cols] = malloc(sizeof *p); //prefered
Or
int (*p)[Cols] = malloc(sizeof(int) * Cols); //alternative
In both of the above expressions, supposing Cols's value is 10, p will point to a block of memory that can take 10 ints.
Usage:
for (int i = 0; i < Cols; i++)
{
p[0][i] = i;
}
The above expresssions only allocated space for one line of ints, but since p is a pointer to array, you can allocate space for as many of them as you want (given the memory constraints).
Let's assume you want an array with 5 lines and Cols columns:
int (*p)[Cols] = malloc(sizeof *p * 5);
Usage:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < Cols; j++)
{
p[i][j] = i * j;
}
}
As you (probably) know this kind of construct is primarily used to emulate a 2D array, one of the advantages is that you can then free all the memory with a single free:
free(p);
Whereas constructs like an array of pointers, or a pointer to pointer would force you have multiple frees.
int (*p)[Cols] = malloc( sizeof *p * Rows );
allocates enough space for a Rows x Cols array of int and assigns the address of that array to p. You can then access each element as p[i][j].
To deallocate all you need is
free( p );

does the following code in c produce a memory leak? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want to know if the following piece of code will produce a memory leak:
m = malloc(5);
m = NULL;
Yes, there is a memory leak. The 5 allocated bytes are no longer accessible as you don't have a pointer to them.
If you save the pointer, you can still use, and free, the resources
unsigned char *m = malloc(5);
if (m) {
unsigned char *p = m;
m = NULL; // can no longer access the memory through m
p[2] = 1; // but p is ok
free(p); // p is ok to free
} else {
fprintf(stderr, "Problem! malloc failed!\n");
exit(EXIT_FAILURE);
}

Define a very large 2D array array with double type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to define a 2D array with size 20*100000 in C. I do not want to keep the size fixed.
double **twod = malloc(20 * sizeof(double *));
int i;
if (twod == NULL)
abort();
for (i = 0; i < 20; ++i)
if ((twod[i] = malloc(100000 * sizeof(double))) == NULL)
abort();
// clean up
for (i = 0; i < 20; ++i)
free(twod[i]);
free(twod);
The first malloc call allocates space for 20 double pointers. Each double pointer will point to a subarray.
The second malloc call in the loop allocates 100000 doubles in each subarray.
The free calls do the inverse of malloc--they return memory to free store. First, each subarray must be freed, in a loop. Then the entire array itself must be freed too.
The return value of malloc is examined against NULL. If malloc returns NULL, then the system is out of memory. This is important since you are allocating HUGE amounts of memory. If malloc returns NULL, the application is aborted.
You'll need to define a pointer to pointer and initialize it like this:
int i;
double **array;
array = malloc(sizeof(double *)) * 20);
for (i=0; i<20; i++) {
array[i] = malloc(sizeof(double) * 100000);
}
Don't forget to free the memory when you're done with it.
You can use a Variable-length array (since C99) in order to avoid fragmentation:
double (*array)[cols];
array = malloc(sizeof(*array) * rows);
In this way calling free(array); is enough.

Create stack space within a struct in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have:
typedef struct{
int *stack;
int *stack_ptr;
}MyStruct;
then somewhere else I do:
MyStruct *temp = malloc(sizeof(MyStruct));
temp->stack = malloc(1024) //allocate 1024 bytes
temp->stack_ptr = temp->stack; //stack_ptr points to beginning of stack
temp->stack_ptr += 800; //move stack_ptr down towards bottom of stack
I'm trying to make sense of the debugger output and I don't think this is right, but I can't tell for sure. I just want to have a stack within my struct and then a stack pointer within this stack that I can manipulate.
EDIT: Okay, the part about adding 800 makes sense. I guess what I'm having trouble understanding is after I allocate 1024 bytes for temp->stack, how do I go about inserting something down towards the bottom of that stack? Do I even need to have the stack_ptr or is there a way to offset stack variable.
Your problem is likely that you think
temp->stack_ptr += 800; //move stack_ptr down towards bottom of stack
would advance your stack pointer to the 800th stack entry. It doesn't, it moves the stack pointer to 800 * sizeof(int) bytes (likely 3200), while you allocated only 1024 bytes.
If you need to dynamically allocate n items of something, the idiomatic C code is
sometype *foo;
/* ... */
foo = malloc (n * sizeof (*foo));
The sizeof multiplication is usually omitted for pointers-to-char since sizeof(char) is 1 by definition of the C Language Standard.
temp->stack = malloc(1024) //allocate 1024 bytes
Should be:
temp->stack = malloc(1024 * sizeof(int)); //allocate 1024 bytes
What exactly is your problem ??
Edit
Let me explain what i meant by that:
Your are trying to move your pointer of 800 blocks (800 * sizeof(int)) but you only allocate 1024 = 1024 / sizeof(int) blocks

Resources