Sometimes getting segmentation fault

I so confused about SEGFAULT in my program. I am trying to implement scanf. So I am passing const char as the first parameter, than parse it for % entries and than use variables arguments to store value in it.
I am so confused about this.
I am not an expert in C an C++ programming. But I understand memory allocation and usage. Here is my code snippet. I am using getline passing to it NULL pointer to char and 0 as size. According to manual it should malloc memory by itself.
I think that is the bad idea that some func allocating memory. But let consider it is ok.
As this func has malloc memory , so I have to free it, but when I am trying to do this , I am getting segmentation fault , but If I leave it as it is , there is no memory leaks in program. I am using valgrind to check memory leaks.
It always crashes on printf ,but in debug mode is seems that variable is correct and consists string.
Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
s = va_arg(argp, char *);
                if (lengthIsSet) {
                    size_t newLen ;
                    size_t readLen;
                    char *strInput = NULL;
                    length = atoi(lengthStr.c_str());
                    readLen = getline (&strInput,&newLen,inputSteam);
                   if (!strInput) {
                       break;
                   }                 
                   int sizeToCopy = (length<readLen)?length:readLen;
                   memcpy(s,strInput,sizeToCopy+1);
                   s[sizeToCopy] = '\0';
}


I have tried to initialize size_t newLen = 0; it seems to work know, but I don't thinks it causes the problem. Please help to solve this. I would be very grateful for any help and explanation.

Here is full function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void scanfCustom(const char* input, FILE *inputSteam, va_list argp) {
    const char *p;
    int * i;
    bool formFound = false;
    std::string lengthStr("");
    int length;
    bool lengthIsSet = false;
    unsigned u;
    char *s;
     p = input;
         for (; *p != '\0'; p++) {
        if ((formFound) && ( *p >= '0' && *p <= '9' ) ) {
                lengthStr+=(*p);
                lengthIsSet = true;
                continue;
             }
        if (*p == '%') {
            formFound = true;
            continue;
        }   
        formFound = false;
        switch (*p) {
            case 's':  
                 s = va_arg(argp, char *);
                if (lengthIsSet) {
                    size_t newLen = 0;
                    size_t readLen;
                    char *strInput = NULL;
                    length = atoi(lengthStr.c_str());
                    readLen = getline (&strInput,&newLen,inputSteam);
                   if (!strInput) {
                       break;
                   }                 
                   int sizeToCopy = (length<readLen)?length:readLen;
                   memcpy(s,strInput,sizeToCopy+1);
                   s[sizeToCopy] = '\0';
printf("%s",s); // It crashes here 
                   // free(strInput);
                   //fgets(s,length,inputSteam);
                }
//TODO READ FULL STR
        }
    }
}



Please suggest how to read user input correctly using C++, maybe there is more easier and convenient way to do this . Without using explicitly scanf, vscanf and so on. Please help, because I have spent hours dealing with this problem. I have found only this functions to read user input from stream.
Of course I've debug my app using gdb, but it seems quite correct, memory copies and have exactly what I need,
I am not pro in C++ and C so don't know a lot of features.
You should rewrite your code to use std::string - it will make your life so much easier. Mainly because you won't have to manually allocate memory and manage pointers anymore. And partially because you won't have a segmentation fault anymore.

By the way, pointers are not to be used in everyday C++.
http://www.LB-Stuff.com/pointers

Also, printf isn't typically used in C++ - instead the Standard Library stream classes are used (e.g. std::cout, std::stringstream etc).
Last edited on
I am calling va_start() and va_end() in another func which in turn invoke this. I have found such example in default library. I have rebuilt my prog using default C++ streams, but it still crashes. I have no idea what is wrong....And I cannot catch segfault from debugger only if runs program directly , I am using NetBeans. Or it is very hard to catch it.

1
2
3
4
5
6
7
8
9
10
11
12
13
case 's':  
                 s = va_arg(argp, char *);
                if (lengthIsSet) {
                    int sizeOfInput = 0;
                    int sizeToCopy = 0;
                    length = atoi(lengthStr.c_str());
                    std::cin >> helloWorld;  
                   sizeOfInput = helloWorld.size();
                   sizeToCopy = (length<sizeOfInput)?length:sizeOfInput;
                   this->copyString(helloWorld,s,sizeToCopy);
                   printf("%s",s);

                }



1
2
3
4
5
6
void printf(const char* input, FILE* stream, ...) {
    va_list args;
    va_start(args, stream);
    this->stringWorker->printfCustom(input,stream,args);
    va_end(args);
}


So now I am not sure where is it crashes now , Is there any way to get stacktrace easily without handling signals like in Java ? Sorry for stupid questions.
What IDE are you using?
I think I got it. I have always problems with internal Netbeans terminal . Sometimes it doesn't print anything just exit with code 0. Like everything is okey. But it should print a lot of text for example.I changed IDE to QT and it seems everything works correctly. Also running from default from default terminal works well. It seems that problem is solved. Netbeans ......


Please say something about code , is it correct in general ?
I don't know about the correctness of the code because of its complexity. It mixes C and C++ and has inconsistent indentation, and thus is very hard to read. You may want to clean it up.
> *lineptr can contain a pointer to a malloc
You've got char *strInput = NULL;
that is not pointing to something allocated by malloc(), so your quote is irrelevant.

If *lineptr is set to NULL and *n is set 0 before the call, then getline() will allocate a buffer
you had `newLen' uninitialized (which is not equivalent to 0).
When everything else fails, RTFM


> And I cannot catch segfault from debugger only if runs program directly
try through valgrind.
It seems that the problem was just in internal terminal that just exit with code 0. And before posting I was getting segfault because of uninitialized variable. After initializing it with zero, it really worked , but I thought that it still crashes because of weird internal terminal in Netbeans. So now it works well. Thanks everyone.
Topic archived. No new replies allowed.