Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static memory vs heap memory?

Tags:

c

memory

Im working in a memory restricted environment and need to create strings dynamically, but still have them not take up heap memory. So does this make sense:

static char staticStringBuffer[10240];
static size_t staticStringWatermark = 0;

void createString( const char * something, const char * somethingElse ) {
    char buf[1024];
    strcat(buf, "test");
    strcat(buf, something);
    strcat(buf, somethingElse);

    strcat(&staticStringBuffer[staticStringWatermark], buf);
    staticStringWatermark += strlen(buf+1);
}

This probably dosent compile, but is what I am attempting sane - sacrificing static memory for heap memory?

Thank-you ^_^

like image 846
ashleysmithgpu Avatar asked Feb 16 '10 10:02

ashleysmithgpu


People also ask

What is difference between memory and heap?

The major difference between Stack memory and heap memory is that the stack is used to store the order of method execution and local variables while the heap memory stores the objects and it uses dynamic memory allocation and deallocation.

Is static memory in stack or heap?

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM . Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it's allocation is dealt with when the program is compiled.

What is difference between static & dynamic memory?

In static memory allocation, while executing a program, the memory cannot be changed. In dynamic memory allocation, while executing a program, the memory can be changed. Static memory allocation is preferred in an array. Dynamic memory allocation is preferred in the linked list.

What is a static memory?

1. Static memory, in which an object is allocated by the linker for the duration of the program. Global variables, static class members, and static variables in functions are allocated in static memory. An object allocated in static memory is constructed once and persists to the end of the program.


2 Answers

That of course depends on what your particular environment does when it loads your program; where is the program's static data put? On many operating systems, the program is loaded into heap memory and run from there, so your static data will still end up on the heap.

like image 83
unwind Avatar answered Oct 17 '22 19:10

unwind


That will work. Some caution is needed not to write past the end of the static buffer, which would happen in your example if strlen(something) + strlen(somethingElse) >= 10240.

like image 25
wallyk Avatar answered Oct 17 '22 20:10

wallyk