Question:
C++: strlen() segmentation fault?
A
2009-01-21 11:52:31 UTC
if(strlen(stringName) != 10)
booleanName = false;

This code is giving me a segmentation fault, and I don't have any clue why. I tested with debug cout lines... the line immediately before prints out, the line immediately after doesn't, as it's cut off by a segmentation fault.

What sort of things could cause strlen() to break down?
Four answers:
ElricTheFullMetal
2009-01-21 12:02:09 UTC
You set a string to 0 rather than "" as in, const char* name = 0, and then call a string method on it, for example, strlen(name).



In general, segmentation faults occur when you follow bad pointers, typically when something is deleted that wasn't allocated with new.
x2000
2009-01-21 13:37:33 UTC
A string in C or C++ that uses strlen() is nothing more than an array of char that has 0 or NUL at the end. If this terminating NUL is not at the end of the array, then strlen() will continue to until it finds one, which could be out of your addressable memory space, which then generates a segmentation fault.



So to avoid this, you need to initialize the string properly, or make sure it has a proper value that does not overflow the array and corrupt memory.
?
2016-11-07 05:23:57 UTC
an EXE has a memory style small medium great a pointer eg Char * must be small medium or great or different eg Char some distance * while doing Malloc your Char * ought to be the main stunning style and your memory style ought to be adequate to hold all your records in you're referencing Segments mutually as in easy terms enforcing a SMALL memory style that doesnt cater for SEGMENTS interior the comparable way. you ought to be waiting to DEBUG it applying the LST and MAP information to locate the wrongdoer traces of code. perchance a Malloc(some whopping huge extensive style) is the reason? i recommend you replace all Mallocs with something that assessments what the malloc parameter is first as you have dropped a clanger with the paramters value
mti2935
2009-01-21 12:05:30 UTC
is a string being assinged to stringName prior to this line that's crashing? Is the string null-terminated?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...