Some earlier part of your program overwrote data malloc uses to keep track of which memory chunks are free.
Quote:
Originally Posted by #siya
seg fault in this line does not occur when i run the code on college's pc..
|
Typically that means in the college's pc the same bug overwrote something that doesn't have an symptom within the execution of this simple program.
The lack of a symptom doesn't imply lack of a bug.
A different version of malloc might reuse freed memory in a different pattern, so it never gets around to hitting the corrupted area within the rest of the execution of the program. Or it might store its control info a little differently relative to the allocated data in a way that delays or avoids the symptom of your bug.
But is your Linux 32 bit or 64 bit and same question for the college's pc?
If you recompiled the code from 32 bit to 64 bit, then the bug might be a portability bug that would never have any symptom in 32 bit. In 32 bit, pointers, longs, and size_t all have the same size as int. One of the most common portability bugs is code that assumes (intentionally or accidentally) that one of those other types is the same size as int.
You still need to find the section of code that overwrites memory it shouldn't. But having a guess at the nature of the problem can change the way you look for it.
An expert would first use gdb to examine the failure inside malloc to see exactly which location had been overwritten by the earlier bug, then restart with gdb and a data breakpoint to see exactly where that location is written. But that approach is too far beyond beginner level to suggest. Instead, I'll assume your whole program is short enough you could post it so someone would easily spot the bug, or you could examine it for the expected kind of bug.
Quote:
when i comment this line then seg fault occurs in the line where malloc is used next..
|
That tells us very little new information. It hints (but doesn't prove) that the original bug is stable (always clobbers the same thing). We already could assume some bug had clobbered data used by malloc, so a subsequent use of malloc would trigger the symptom.
Many memory clobber bugs are unstable: An unrelated change elsewhere in the program tends to change the use or location of the memory that the bug clobbers, leading to lots of false conclusions about what "fixes" or "causes" the bug, when those unrelated changes really just hide or reveal the symptom.
But the most common memory clobber bugs, which write past the end of an allocated chunk of memory, tend to be stable. They clobber memory used by malloc, not by random accident but systematically, because memory used by malloc to keep track of used and free chunks consists of little control blocks right before and after each used chunk.