gcc 4.6.2 c89
I am just wondering what could cause more memory issues. For example, if you allocate a structure array on stack or if you was to allocate it dynamically on the heap.
Normally, I follow a simple rule. If the structure is only to be used in that function, then I allocate on the stack. However, if I need to refer to it somewhere else by keeping it in memory I would allocate dynamically.
The reason I asked this question as some of my memory was getting corrupted and I was told that I should allocate dynamically rather than on the stack for structure arrays. As stack memory has more chance of getting corrupted. However, if memory that is allocated dynamcially gets corrupted you can easily free it.
Does the above make sense to anyone?
Many thanks for any suggestions,
I wouldn’t say that any one way of allocating a structure has “more chance of corruption”. Whatever is causing the corruption could happen just as easily however it’s allocated.
I’d say you’d be better off fixing the source of the corruption: You can use gdb to put a breakpoint on write to the corrupted variable with
watch <varname>. Alternatively, you can also put a breakpoint when you detect corruption, and then use reverse debugging to find where the corruption occurred.Edit: There seems to be some confusion about the meaning of stack and
staticallocation:Stack variables are valid only during the lifetime of the function – once this function has returned, you can’t expect the data at the location of
ato still be valid. Sometimes these are called local or automatic variables.Static variables inside a function are valid also outside the function – the data is kept around between function invocations. This means if you do this:
The number printed will increase by one on each invocation of
foo(). Generally, functions don’t have many variables declared as static, because static variables remember their last value from the last time the function was called – which is usually not the behaviour you want. It’s possible this is what was meant by the person who told you that static variables have “more chance of being corrupted”.Heap variables are valid from when they’re created to when they’re
free()d. This is also called dynamic allocation and is what you want if you’re planning to return data to another part of the program (or if you want to specify the length of an array at runtime in C89).Aside:
staticis confusing in that when applied to a function name or variable in global scope:it means “this function or variable is only visible inside this translation unit”. I’m not sure why the
statickeyword has these two different meanings.