Thread: Segmentation fault stepping into function in debug mode

  1. #1
    Registered User
    Join Date
    Nov 2021
    Posts
    3

    Segmentation fault stepping into function in debug mode

    Hi,
    I have to parse a string and fill a structure with data. But when i try to step into function parse_mp_info while debugging i receive a segmentation fault. The weired thing is that if i don`t initialize pch pointer with NULL no error occures. What can it be and how to fix/bypass it?
    (I use Qt Creator 7.0.1 on Ubuntu 20.04. Plain C project)
    =====================================
    Code:
    #include <stdio.h>
    typedef struct MPRInfo{
        long long cnt;
        char   smb[8];
        size_t r1;
        size_t r2;
        size_t r3;
    
    
        double l1;
        double l2;
        double l3;
    } stMPR;
    
    
    
    
    int parse_mp_info(stMPR* stData,const char* pData){
        char *pch=NULL;
        //char *pch; //Here no problem
        
        //Main code....
        
        return 0;
    
    
    }
    
    
    int main()
    {
        const char *pData     = "Some data......";
        stMPR stParsed       = {0};
        int res               = parse_mp_info(&stParsed,pData);
    
    
        if(res!=0)
            printf("Error parsing data!\n");
        return 0;
    }
    ===========================================

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    All local variables should ALWAYS be initialized, especially for pointers! It is illegal to access a NULL pointer resulting in a segmentation fault. You need to assign pch with the address of some valid nul terminated char string first.

    In most cases, if not initialized, pch is getting some garbage data on the stack, and is being interpreted as an address, most always an address that it should not be accessing, resulting in a segmentation fault. Why it does not create a fault in your case, is unclear.

    Your code as presented does compile and run correctly. You need to provide the missing code if you continue to have problems.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Lemme guess, you're trying to do strtok() in your parser on a const char* pData string.

    Also this -> Short, Self Contained, Correct Example
    If you want an accurate diagnosis, then post a runnable example demonstrating the problem at hand.

    Redacting your code to the point of useless means you just get random guesses and hand-waving.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Nov 2021
    Posts
    3
    Quote Originally Posted by Salem View Post
    Lemme guess, you're trying to do strtok() in your parser on a const char* pData string.
    Yes, you are right! In fact the code looks like this:
    Code:
    #include <stdio.h>
    #include <string.h>
    typedef struct MPRInfo{
        long long cnt;
        char   smb[8];
        size_t r1;
        size_t r2;
        size_t r3;
    
    
        double l1;
        double l2;
        double l3;
    } stMPR;
    
    
    
    
    int parse_mp_info(stMPR* stData,const char* pData, const char* pName){
        if(pName!=NULL){
            strcpy(stData->smb,pName);
    
    
        }
        char buffer[128] = {0};
        char *p_tmp      = NULL;
        char *p_tag      = strstr(pData,"ticks");
    
    
        if(p_tag){
            p_tmp = strchr(p_tag,':');
            if(p_tmp){
                char *p_start   = ++p_tmp;
                char *p_end     = strchr(p_tag,',');
                unsigned len    = p_end-p_start;
                for(unsigned i=0;i<len;i++){
                   buffer[i]=p_start[i];
                }
                stData->cnt = strtoll(buffer,NULL,0);
            }
        }
    
    
        p_tag = strstr(pData,"rates");
    
    
        if(p_tag){
            char *pch  = strtok(p_tag,":,");
            unsigned proc_val = 0;
            while(pch!=NULL){
               if(strcmp(pch,"\"r1\"")==0){
                  proc_val=1;
               }
    
    
               if(proc_val==1){ //should store value in struct field
                   char *pdiv = strchr(pch,':');
                   memset(buffer,0,128*sizeof(char));
                   for(int i=0;i<strlen(pch);i++){
                      buffer[i]=pch[i];
                   }
                   stData->r1 = strtol(buffer,NULL,0);
               }
    
    
    
    
               pch  = strtok(NULL,":,");
            }
    
    
    
    
    
    
    
    
        }
    
    
        return 0;
    
    
    }
    
    
    int main()
    {
        const char *pData     = "{\"ticks\":1657195557242,\"rates\":[{\"r1\":145,\"r2\":716,\"r3\":2145}],\"lows\":[{\"l1\":0.05,\"l2\":0.0135,\"l\":1.02}]}";
        stMPR stParsed        = {0};
        int res               = parse_mp_info(&stParsed,pData,"Test1");
    
    
        if(res!=0)
            printf("Error parsing data!\n");
        return 0;
    }
    Under Windows i get to the bold line and then receicve the error. Under linux i receicve the error the moment i try to step into the function..

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    strtok() WRITES to the string.
    If the string is read-only (which it is), then you get a segfault when you try to modify it.

    You need to make a copy of the input string in a temporary buffer, then strtok() your way through the temporary buffer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Shouldn't the compiler be able to warn when passing a const char* to a function that accepts a char* ?

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    The constness is lost by doing this
    char *p_tag = strstr(pData,"ticks");
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    I see. So it's more an API problem.

  9. #9
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    948
    Quote Originally Posted by thmm View Post
    I see. So it's more an API problem.
    Yep, this is one of the shortcomings/limitations of C.

    C++ has two overloaded versions of strstr, one that takes and returns const char * and the other that takes and returns a non-const char *. C doesn't have overloaded functions, but it still could have had two differently-named strstr functions (one for const and another for non-const), but what's done is done at this point.

  10. #10
    Registered User
    Join Date
    Nov 2021
    Posts
    3

    Thumbs up

    Thanks a lot for commentaries! Now it`s cleared up more or less! Frankly i didn`t expect it to turn out that tricky..))
    I guess i should try to use some other way

  11. #11
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Your data looks like JSON, so using a JSON library might be a good idea.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to debug "segmentation fault" in a parallel code?
    By smartfish in forum C Programming
    Replies: 2
    Last Post: 02-06-2012, 12:54 PM
  2. Segmentation Fault Debug
    By nair in forum C++ Programming
    Replies: 4
    Last Post: 08-02-2011, 09:04 PM
  3. can't debug the source of segmentation fault in my code
    By sourabhsinha in forum C Programming
    Replies: 2
    Last Post: 04-28-2011, 08:50 AM
  4. Replies: 1
    Last Post: 04-24-2010, 01:35 PM
  5. Replies: 4
    Last Post: 09-16-2006, 07:11 PM

Tags for this Thread