Create stack space within a struct in C [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 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

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 to divide memory on the heap? [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
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.

how to clear pointer variable which is holding start of memory location that needs to be cleared for 20 bytes of data from starting location [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Pointer variable is holding the value which is nothing but an address of memory location that needs to be cleared for next 20 bytes of data.
I have tried below code snippet but it clears the value of pointer value (address of starting memory location). By doing so, i lost the start address of memory location (pointer value).
srcadr = 0x105fc080;
i = 20;
*srcptr = &srcadr
if(srcptr != NULL)
{
while (i < 20)
{
*srcptr++ = 0x00;
}
}
Your code is incomplete.
But let's assume this first line is valid:
srcadr = 0x105fc080;
that means srcadr can be an unsigned int (or unsigned long).
Then we need to treat that as a pointer, and clear 20 bytes from that address:
volatile unsigned char * const area = (unsigned char *) srcadr;
for(int i = 0; i < 20; ++i)
area[i] = 0;
The cast is necessary in order to treat the address value as a pointer. Using &srcadr makes no sense at all, that gives us the address of the srcadr pointer variable, which is irrelevant.
Note for future readers: if you can, of course you'd just use memset()this like so:
memset((void *) 0x105fc080, 0, 20);
and be done. But the OP can't use that for whatever reason, perhaps it's an embedded environment with a limited standard library (and, uh, dull compiler without an intrinsic) for instance.
If all you want to do is set 20 Byte of memory to 0 you can use memset.
All you have to do is:
#include <string.h>
mem_len = 20
mem_value = 0
ptr = 0x105fc080
memset(ptr. mem_value, mem_len)
Use memset function from string.h library.
#include <string.h>
char *srcadr = 0x105fc080;
int size = 20;
memset(srcdr,0,size);

Allocating memory to ** [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 have this struct
typedef struct{
char **palavras;
}no;
and I want to allocate memory to this array of strings basically
and I can't do this, since it says it expects something before the '('
no *atual;
atual->(*palavras)=calloc(1,sizeof(char*));
You need to do it in several stages:
First, allocate memory to atual,
Next, allocate memory to palavras
Finally, allocate memory to elements of palavras
Assuming that you need to allocate 10 palavras, you can do it like this:
no *atual = malloc(sizeof(no));
atual->palavras = malloc(sizeof(char*)*10);
atual->palavras[0] = malloc(20);
...
You should access palavras by atual->palavras, e.g. atual->palavras = calloc(5, sizeof(char *)), and dereference the char ** by *atual->palavras. You may also allocate memory for the char * pointers by atual->palavras by, say, atual->palavras[0] = malloc(10 * sizeof(char)).

How to malloc these structures? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
struct atom {
int x;
int y;
int z;
double mass;
};
struct molecule {
struct atom *member;
int natoms;
};
struct system {
struct molecule *fragment;
int nfrags
};
struct system sys;
sys.nfrags=get_number_of_fragments;
????
The system has some number of molecules, each of which has some number of atoms. I don't know how to allocate these things. If I allocate sys.fragment first, it seems like the sizeof(molecule) is undefined since I haven't yet defined the number of atoms (so how can it have a size?). If I try to define the number of atoms first, how do I specify which fragment I'm mallocing for?
I have functions that will return the number of atoms for any molecule/fragment as well as the number of fragments, but am stuck on where to go from here.
AFAIK sizeof(X) cannot be "undefined". In this example, sizeof(molecule) is well defined as the amount of memory it takes to store one molecule instance: One atom Pointer (Note: not the size of any array that you may put here, just the size of the pointer) and one int. So it is perfectly fine to do it the first way and allocate your sys.fragment first:
sys.fragment = malloc(sys.nfrag * sizeof(sys.fragment));
sys.fragment = calloc(sys.nfrag, sizeof sys.fragmemt[0]);
or
sys.fragment = malloc(sys.nfrag * sizeof sys.fragment[0]);
when performance matters (but do not forget the check for overflow!).
malloc(sizeof(system)) Easy as that
You basically have a:
size = X;
first = malloc(X * sizeof(First));
first->second = malloc( N * sizeof(Second));
and so on

Resources