Reputation: 29
I have a code like below:
struct abc
{
int *xyz;
}
void func1(abc *ptr, .... lots of other struct ptrs passed)
{
func2(ptr->xyz) // some computation, only read from ptr->xyz
...
...
func3(ptr->xyz) // some computation, ptr->xyz is only read
}
void main()
{
abc *ptr;
// memory is allocated properly here for ptr and ptr->xyz.
func1(ptr,...);
}
Problem: Seg fault happens at func3, due to ptr->xyz=0x0. Till func2, ptr->xyz address is proper. and no other related code before func3. Not reproducible. Not much info from core dump regarding start of memory corruption, or valgrind.
Analysis: I ran GDB and used command awatch *(address of ptr->xyz) for normal working case. Throughout func1, func2, func3, we only read from ptr->xyz memory address. No write operation happens, in normal working scenario. So I believe this might be due to some other memory corruption overlap.
Question: If I pass as void func1(const abc *const ptr). I dont want to change address/data of abc or abc->xyz. Does "const" ensure that struct abc,abc->xyz always gets stored in some read-only segment in memory, and hence safe from any memory corruption ? maybe due to other struct memory address overlap write ?
Thanks!
Upvotes: 0
Views: 211
Reputation: 154126
Does "const" ensure that struct abc,abc->xyz always gets stored in some read-only segment in memory, and hence safe from any memory corruption ?
No, not always. With const
, diagnostics (warnings/errors) at compile time emit if code knowingly attempts to modify the variable.
If an attempt is made to modify an object defined with a const-qualified type through use of an lvalue with non-const-qualified type, the behavior is undefined. C11 §6.7.3 6
Should code attempt, at run time, to modify a const
variable, it might work, it may fail silently, it may crash the program. It is undefined behavior.
In OP's case, suspect code is writing outside bounds and into field xyz
, so making xyz
const
is not going to help much.
Upvotes: 4