Thread: malloc char** seg faults

  1. #16
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by laserlight View Post
    You wouldn't have needed to take them out (and after all they could come in useful if someone wanted to compile and run your code to see if they get the same effect!) if you wrote them to correctly give debugging info in the first place. For example, that offending printf I highlighted only needed to be:
    Code:
    printf("after malloc %s\n", path);
    After all, if there was no segfault before the malloc call, you still wouldn't want to try and print *names before initialising it to a valid non-null pointer, so there's no useful debugging info to get by trying to print it there. Likewise, in listdir, there was no point printing *names since on the very first call it would not be valid at that point, and on subsequent calls it would not change and hence not be useful. If you really wanted to manually check that names was not a null pointer as part of debugging, you could have gone with:
    Code:
    printf("after malloc %s %p\n", path, (void*)names);
    that is a valid statement, but it still does not explain why it is seg faulting when no printf is in there on either side of malloc. is this not a valid malloc call?
    Code:
    char **names;
    int sum = 10;
    names = (char **)malloc(sum * sizeof(char *));
    this is from e16 / Enlightenment ( window manager) epplets, the original code I modded to get it to be Recursive.
    Code:
     if (!dirlen)
         {
        closedir(dirp);
        *num = 0;
        return ((char **)NULL);
         }
       names = (char **)malloc(dirlen * sizeof(char *));
       D((" -> Storing names at %8p.\n", names));
    
       if (!names)
         {
        *num = 0;
        return ((char **)NULL);
         }
       rewinddir(dirp);
       for (i = 0; (dp = readdir(dirp));)
         {
        if ((strcmp(dp->d_name, ".")) && (strcmp(dp->d_name, "..")))
          {
             Esnprintf(fullname, sizeof(fullname), "%s/%s", dir, dp->d_name);
             D((" -> About to stat() %s\n", fullname));
             if (stat(fullname, &filestat))
               {
              D((" -> Couldn't stat() file %s -- %s\n", dp->d_name,
                 strerror(errno)));
               }
             else
               {
              if (S_ISREG(filestat.st_mode))
                {
                   D((" -> Adding name \"%s\" at index %d (%8p)\n",
                  dp->d_name, i, names + i));
                   names[i] = strdup(dp->d_name);
                   i++;
                }
              else if (S_ISDIR(filestat.st_mode))
                {
                   /* Recurse directories here at some point, maybe? */
                }
               }
          }
         }
    Last edited by poorboy; 11-28-2018 at 08:48 PM.

  2. #17
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,493
    Quote Originally Posted by poorboy
    that is a valid statement, but it still does not explain why it is seg faulting when no printf is in there on either side of malloc. is this not a valid malloc call?
    It isn't seg faulting once the printf calls have been fixed or removed. Look at the code I posted in post #14. I compiled and ran that code without a segmentation fault. It uses malloc, and notice that I commented out two printf calls in the listdir function. Before I did that, the otherwise identical code taken from your post #12 (but with malloc enabled) was giving me a segfault.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #18
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by john.c View Post
    You're really too much of an a-hole to bother with.
    It's the printfs, you braindead idiot.
    Why can't you understand that?
    so you're the brain around here, then explain to me HOW, when something takes place before something else takes place. One can say with absolute certainly that is was what took place after the first that caused it to take place?

    line of action
    1. something blows up
    2. man lights a match.

    3. someone see man lighting match after the fact, his logic says it was because the man lit the match after the explosion that caused the explosion to take place.
    4. the one that was there before the match was lit says, no it was not.then tell him what really happened.
    5. someone else comes in and does not listen to what the man that seen it all take place either, instead he listens to the man that has no idea what really took place, and calls the one that does an a-hole for trying to give him the facts.

    your code works, but it does not mimic mine , therefore it is invalid even though it is working code. One cannot even expect to get the same results using a test that does not mirror the first one. it changes the conditions. no one can expect the same results by changing the conditions.
    thanks for the effort though.

  4. #19
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,493
    Quote Originally Posted by poorboy
    so you're the brain around here, then explain to me HOW, when something takes place before something else takes place. One can say with absolute certainly that is was what took place after the first that caused it to take place?
    Huh?

    Quote Originally Posted by poorboy
    your code works, but it does not mimic mine , therefore it is invalid even though it is working code.
    My code is almost exactly the same as yours! I just commented out two debugging printf calls. If it is invalid, so is your code.

    Quote Originally Posted by poorboy
    One cannot even expect to get the same results using a test that does not mirror the first one. it changes the conditions. no one can expect the same results by changing the conditions.
    Rubbish. I didn't change any conditions. I repeat: I commented out two debugging printf calls. That is literally all that I did. Nothing else. Absolutely nothing else. If anything else has changed, it is because you changed it.

    EDIT:
    Oh wait, you're responding to john.c. But john.c is right: it really is your offending printf calls. Maybe it wasn't the case before you put them in, but whatever else you might have fixed, because they are there they led to the segfaults that we now observe. Remove them and the segfaults disappear.
    Last edited by laserlight; 11-28-2018 at 09:17 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #20
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by laserlight View Post
    It isn't seg faulting once the printf calls have been fixed or removed. Look at the code I posted in post #14. I compiled and ran that code without a segmentation fault. It uses malloc, and notice that I commented out two printf calls in the listdir function. Before I did that, the otherwise identical code taken from your post #12 (but with malloc enabled) was giving me a segfault.
    In listdir function, thanks, let me go back and look at that .

    Now I am more confused then before. I compiled it again,
    Code:
    gcc -wall filename.c
    ran it still leaving in the printf
    Code:
    printf("listdir %s, %s, %d\n", name,*names,indent);
    
    //printing this, using an exit(0); to stop it so I could get that output,
    listdir /media/data1/HPImages, (null), 0
    but without the exit(0); it now no longer seg faults with the printf in listdir still in place. so .... just a strange quirk?

  6. #21
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by john.c View Post
    You're really too much of an a-hole to bother with.
    It's the printfs, you braindead idiot.
    Why can't you understand that?
    yes that was to the one that called me an a(ss) hole, braindead idiot for no good reason,
    Quote Originally Posted by laserlight View Post
    Huh?


    My code is almost exactly the same as yours! I just commented out two debugging printf calls. If it is invalid, so is your code.


    Rubbish. I didn't change any conditions. I repeat: I commented out two debugging printf calls. That is literally all that I did. Nothing else. Absolutely nothing else. If anything else has changed, it is because you changed it.

    and it still gives him no right to call me an ass hole braindead idiot.

    EDIT:
    Oh wait, you're responding to john.c. But john.c is right: it really is your offending printf calls. Maybe it wasn't the case before you put them in, but whatever else you might have fixed, because they are there they led to the segfaults that we now observe. Remove them and the segfaults disappear.
    not the ones put into question and my post above expline something went strange because it is not seg fault with the same printf in listdir in place and the other printf that were put into question removed, and it was seg fault'ing before that.

    it still does not give him the right to call me an ass hole braindead idiot.
    Last edited by poorboy; 11-28-2018 at 09:26 PM.

  7. #22
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,493
    Quote Originally Posted by poorboy
    but without the exit(0); it now no longer seg faults with the printf in listdir still in place. so .... just a strange quirk?
    This quirk is called undefined behaviour. More formally:
    Quote Originally Posted by C11 Clause 3.4.3
    undefined behavior
    behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

    NOTE
    Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

    EXAMPLE
    An example of undefined behavior is the behavior on integer overflow.
    You're looking at the "unpredictable results" possibility. A segmentation fault would be "terminating (...) execution (with the issuance of a diagnostic message)".
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #23
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by laserlight View Post
    This quirk is called undefined behaviour. More formally:

    You're looking at the "unpredictable results" possibility. A segmentation fault would be "terminating (...) execution (with the issuance of a diagnostic message)".
    well nevertheless, it is not in the actual code being put into "production" and I'll remember to not printf as I did in listdir for a char**

    not bad for a ass hole brainsead idiot , which my act is a direct contradiction to what he Judged me as.

  9. #24
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by john.c View Post
    It's not name calling. You are clearly extremely stupid. I was just "reporting" that fact.
    you do not even understand the basic fundamentals of what "name calling is" making you ignorant of the facts. in fact the printf in question were not what was causing it to seg fault, again you are still wrong in that ass-essment. nor what you CALLED me is justified,only in your poorly formed mind. I bet you do not make friends easily.
    Code:
    name-call·ing
    /ˈnām ˌkôliNG/
    noun
    noun: name-calling
    
    
    • abusive language or insults.
    in case you do not know what a insult is
    Code:
    in·sult
    verb
    3rd person present: insults
    /inˈsəlt/
    1. 
    speak to or treat with disrespect or scornful abuse.

  10. #25
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,493
    Quote Originally Posted by poorboy
    in fact the printf in question were not what was causing it to seg fault
    No, they were what was causing it to seg fault. I demonstrated that by removing the offending printf calls and was rewarded with no seg faults. Have you tried the code that I posted in post #14?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #26
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by laserlight View Post
    No, they were what was causing it to seg fault. I demonstrated that by removing the offending printf calls and was rewarded with no seg faults. Have you tried the code that I posted in post #14?
    the printf in MAIN were not the cause of the seg fault, that is what I am and have been saying all along, BECAUSE it was seg faulting before that, as I have stated, therefore it was not the reason, as you and that other abusive language boy was and still are accusing me of.

    it may have been the one in listdir that was the cause of it. which was not even pointed out until way after I as attacked with abusive language in here by someone else that feels it is justified to resort to name calling when he is not being listened to. instead of stepping back as reassessing what is really going on. by putting it back to where I first noticed it taking place which would be to remove all of the printf in main concerning the malloc call to see what happens.

    Instead of focusing on the after the fact and insisting to me that is why it happened. when there is no logical way the after the fact can be the cause of something happening.

  12. #27
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,493
    Quote Originally Posted by poorboy
    the printf in MAIN were not the cause of the seg fault, that is what I am and have been saying all along, BECAUSE it was seg faulting before that, as I have stated, therefore it was not the reason, as you and that other abusive language boy was and still are accusing me of.
    It might or might not be. The debugging printf in main that I highlighted is wrong, and because of how undefined behaviour works, it could be the cause of the seg fault, at least sometimes. For good measure, here is your own code that you posted in post #1, with three debugging printf calls (including the one in main, although in my test it didn't result in a seg fault) commented out:
    Code:
    #include <unistd.h>
    #include <sys/types.h>
    #include <dirent.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <sys/stat.h>
     
    //global to not reset count to zero
    //in recursive function
    int i = 0, b = 0;
    int getcount = 1;
     
    char       **
    randomize_file_list(char **names, unsigned long len)
    { printf("randomize file list\n");
       int                 r;
       unsigned long       i;
       char               *tmp;
     
       for (i = 0; i < len - 1; i++)
         {
        r = (int)((len - i - 1) * ((float)rand()) / (RAND_MAX + 1.0)) + i + 1;
        tmp = names[i];
        names[i] = names[r];
        names[r] = tmp;
         }
         printf("leaving randomize file list\n");
       return (names);
    }
     
    char       **
    sort_file_list(char **names, unsigned long len)
    { printf("sort file list 342\n%s \n%ld\n",*names,len);
       unsigned long       i;
       unsigned char       done = 0;
     
       while (!done)
         {
        done = 1;
        //set at 1 because zero is NULL
        for (i = 1; i < len - 1; i++)
          { printf("in for loop 353\n");
              printf("i=%ldstrcmp(names[%s], names[i + 1 %s]) > 0\n",i, names[i], names[i+1]);
             if (strcmp(names[i], names[i + 1]) > 0)
               {
              char               *tmp;
     
              tmp = names[i];
              names[i] = names[i + 1];
              names[i + 1] = tmp;
              done = 0;
               }
          }
         }
         printf("leaving sort_file_list\n");
       return (names);
    }
    //get total files to know how much to malloc 2d char array
     
    void getAmount(const char *name, int indent, unsigned long *sum) 
    { printf("get amount\n");
        DIR *dirp;
        struct dirent *entry;
       char path[1024];
         
           if (!(dirp = opendir(name)))
           {
               printf("cannot open dir.\n");
               exit(1);
           }
      
         
        while ((entry = readdir(dirp)) != NULL) {
            if (entry->d_type == DT_DIR) {
                
                if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                    continue;
                snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
              
                getAmount(path, indent + 2, sum);
            } else {
             
                 
                i++;
            }
        }
       closedir(dirp);
       *sum = i;
       printf("leaving get amount\n");
     }
     
    char ** listdir(const char *name, char *names[], int indent)
    {//printf("listdir %s, %s, %d\n", name,*names,indent);
         
        DIR *dir;
        struct dirent *entry;
        char path[1024];
           
            if (!(dir = opendir(name)))
               return  ((char **)NULL);
      
      //printf("n %s c %d \n", names[b], b);
       
        while ((entry = readdir(dir)) != NULL) {
            if (entry->d_type == DT_DIR) {
               
                if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                    continue;
                snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
              
                listdir(path, names, indent + 2);
            } else {
              
              snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
              printf("%s\n",path);
               
                names[b] = strdup(entry->d_name);
                b++;
            }
        }
        closedir(dir);
        printf("returning listdir\n");
        return (names);
    }
     
    int main(int argc, char **argv) {
        char *path;
        char **gotNames;
        char **names;
        int g; 
        unsigned long sum;
         
        if(argc < 2)
        {
            printf("no path.\n");
            return EXIT_FAILURE;
        }
         
        if (!strcmp(argv[1], "-p"))
        {
            path = strdup(argv[2]);
            getAmount(path,0, &sum);
             
            printf("i=%d\n",i);
            printf("sum=%ld\n",sum);
            printf("before malloc %s\n", path);
             
            //segfaults here
             
            names = (char **)malloc(sum * sizeof(char *));
         
            if (names == NULL)
            {
                printf("Names is NULL\n");
            }
            //printf("after malloc %s %s\n", path,*names);
            gotNames =    listdir(path,names,0);      
            printf("after malloc\n");
                 
        }
        else
        {
            printf("could not get files missing -p.\n");
            return EXIT_FAILURE;
        }
     
        for(g = 0; g < i; g++) {
        ;
            //printf("%s\n",gotNames[g]);
        }
           
        printf("howmany %d\n", i);
             
        sort_file_list(gotNames, sum);
         
        return 0;
    }
    When I compiled and ran the code before commenting out the three debugging printf calls, I got this result:
    Code:
    get amount
    leaving get amount
    i=2
    sum=2
    before malloc testc
    Segmentation fault (core dumped)
    After commenting out the three debugging printf calls, I compiled and ran the code for a directory of two files, and got this result:
    Code:
    get amount
    leaving get amount
    i=2
    sum=2
    before malloc testc
    testc/a.txt
    testc/b.txt
    returning listdir
    after malloc
    howmany 2
    sort file list 342
    a.txt 
    2
    leaving sort_file_list
    This is as clear as can be to show that the segmentation fault was due to at least one of the debugging printf calls, not to malloc. You were told this by Salem in post #2, by me in post #4, and then admittedly rather rudely by john.c in post #11, but it is true: "It's the printfs". If you had at least tried to comment out the printfs after reading posts #2 or #4, or after my explanation in post #7, just to see if it might actually be true that they were causing the segfaults, john.c wouldn't have become so frustrated by post #11.

    Quote Originally Posted by poorboy
    it may have been the one in listdir that was the cause of it. which was not even pointed out until way after I as attacked with abusive language in here by someone else that feels it is justified to resort to name calling when he is not being listened to. instead of stepping back as reassessing what is really going on. by putting it back to where I first noticed it taking place which would be to remove all of the printf in main concerning the malloc call to see what happens.
    They have the same characteristic, as noted by Salem in post #2: "You only just allocated names, and now you're trying to dereference it." In fact, that is why I wrote in post #4 that "You should fix those printf calls": notice the plural, because in fact I traced the first one in listdir and thought you would have seen it too after tracing through the code. (I didn't see the second one in listdir until I actually tested your code.)

    The thing is that because of the unpredictable behaviour, it is difficult to say whether or not you will definitely get a seg fault, so people aren't necessarily going to point out the exact right one to you: the one I highlighted made the most sense for a start because it is the first after the point where you identified the seg fault. Instead of arguing, just fix them! Yes, you might be faced with another, but then you can fix that too.

    Quote Originally Posted by poorboy
    Instead of focusing on the after the fact and insisting to me that is why it happened. when there is no logical way the after the fact can be the cause of something happening.
    Sorry, I don't understand what you're trying to say here.
    Last edited by laserlight; 11-28-2018 at 10:19 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #28
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,657
    For me at least, trying to print a null pointer as a string does produce a useful hint that you're doing something wrong, instead of segfaulting.
    Code:
    $ cat foo.c
    #include <stdio.h>
    
    int main ()
    {
        char *p = 0;
        printf("Does this fault?, null=%s\n", p);
    }
    $ gcc foo.c
    $ ./a.out 
    Does this fault?, null=(null)
    If you see (null) in your printouts, then you need to fix your code. It was only an act of grace that saved you from a segfault.


    But to deal with segfaults, you use the debugger to figure out why.
    This is what I did.
    Code:
    $ gdb -q ./a.out
    Reading symbols from ./a.out...done.
    (gdb) run -p progtest
    Starting program: /home/sc/Documents/a.out -p progtest
    get amount
    leaving get amount
    i=0
    sum=0
    before malloc progtest
    
    Program received signal SIGSEGV, Segmentation fault.
    0x00007ffff7a5bcc0 in _IO_vfprintf_internal (s=0x7ffff7dd2620 <_IO_2_1_stdout_>, format=<optimised out>, ap=ap@entry=0x7fffffffdd28) at vfprintf.c:1632
    1632	vfprintf.c: No such file or directory.
    (gdb) bt
    #0  0x00007ffff7a5bcc0 in _IO_vfprintf_internal (s=0x7ffff7dd2620 <_IO_2_1_stdout_>, format=<optimised out>, ap=ap@entry=0x7fffffffdd28) at vfprintf.c:1632
    #1  0x00007ffff7a62899 in __printf (format=<optimised out>) at printf.c:33
    #2  0x0000000000400fec in main (argc=3, argv=0x7fffffffdf28) at main.c:155
    (gdb) frame 2
    #2  0x0000000000400fec in main (argc=3, argv=0x7fffffffdf28) at main.c:155
    155	    printf("after malloc %s %s\n", path, *names);
    (gdb) print *names
    $1 = 0x3 <error: Cannot access memory at address 0x3>
    (gdb) print path
    $2 = 0x603010 "progtest"
    (gdb)
    Now the essence of that is what I posted, but now you know how I got there.
    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.

  14. #29
    Registered User
    Join Date
    Nov 2018
    Posts
    21
    Quote Originally Posted by poorboy View Post
    the printf in MAIN were not the cause of the seg fault, that is what I am and have been saying all along, BECAUSE it was seg faulting before that, as I have stated, therefore it was not the reason, as you and that other abusive language boy was and still are accusing me of.

    it may have been the one in listdir that was the cause of it. which was not even pointed out until way after I as attacked with abusive language in here by someone else that feels it is justified to resort to name calling when he is not being listened to. instead of stepping back as reassessing what is really going on. by putting it back to where I first noticed it taking place which would be to remove all of the printf in main concerning the malloc call to see what happens.

    Instead of focusing on the after the fact and insisting to me that is why it happened. when there is no logical way the after the fact can be the cause of something happening.
    Quote Originally Posted by laserlight View Post
    It might or might not be.
    it is exactly not the reason it seg fautled in the first place. Because it was not even there when it seg faulted in the first place.

    SO it cannot by any means be the reason that it seg fault , that is you and everyone else forcing on the after the fact then telling me it is causing it to seg fault. Then expecting me to just accept this, had I done so, then just removed them again, it would have put it back into the same state it was in when it seg faulted in the first place. because you and that hot head foul mouthed keeps insisting that it is something that was not even there in the first place that is the cause of the accident. (seg fault).

    pointing to it and saying yes it is, that is why it is seg faulting. when there is no way in heaven or hell it could be he reason it was seg faulting.

    so to say you do not understand that, shows me you do not even understand what it is you are saying, or talking about, and or do not know how to pick out the facts , then remove them in your mind to deduce the actual cause of something.

    when it is pointed out to you that they were in fact not in place when a seg fault took place, and you, and the other tell me that is why it did happened, and you tell me you do not understand why I am telling you and everyone else no it is not.

    you even by acting on it, and removing the printf in main to find that one printf hidding just under the listdir prams, something that was there prior to me adding the printf in main, and then come back and tell me you have no idea, or understanding of what I am talking about. do you have a wire loose somewhere in your mind?


    really? you do not understand you are using 'evidence that took pace after the fact and are saying it is the cause of something that took place prior to it being placed there. I am happy you do not work for the justice system of any country, or governing body.


    Quote Originally Posted by laserlight View Post
    Quote Originally Posted by poorboy
    Instead of focusing on the after the fact and insisting to me that is why it happened. when there is no logical way the after the fact can be the cause of something happening.
    Sorry, I don't understand what you're trying to say here.

    ----------------------------------------------------------------
    =================================
    Quote Originally Posted by Salem View Post
    For me at least, trying to print a null pointer as a string does produce a useful hint that you're doing something wrong, instead of segfaulting.
    If you see (null) in your printouts, then you need to fix your code. It was only an act of grace that saved you from a segfault.


    But to deal with segfaults, you use the debugger to figure out why.
    This is what I did.
    Code:
    $ gdb -q ./a.out
    Reading symbols from ./a.out...done.
    (gdb) run -p progtest
    Starting program: /home/sc/Documents/a.out -p progtest
    get amount
    leaving get amount
    i=0
    sum=0
    before malloc progtest
    
    Program received signal SIGSEGV, Segmentation fault.
    0x00007ffff7a5bcc0 in _IO_vfprintf_internal (s=0x7ffff7dd2620 <_IO_2_1_stdout_>, format=<optimised out>, ap=ap@entry=0x7fffffffdd28) at vfprintf.c:1632
    1632    vfprintf.c: No such file or directory.
    (gdb) bt
    #0  0x00007ffff7a5bcc0 in _IO_vfprintf_internal (s=0x7ffff7dd2620 <_IO_2_1_stdout_>, format=<optimised out>, ap=ap@entry=0x7fffffffdd28) at vfprintf.c:1632
    #1  0x00007ffff7a62899 in __printf (format=<optimised out>) at printf.c:33
    #2  0x0000000000400fec in main (argc=3, argv=0x7fffffffdf28) at main.c:155
    (gdb) frame 2
    #2  0x0000000000400fec in main (argc=3, argv=0x7fffffffdf28) at main.c:155
    155        printf("after malloc %s %s\n", path, *names);
    (gdb) print *names
    $1 = 0x3 <error: Cannot access memory at address 0x3>
    (gdb) print path
    $2 = 0x603010 "progtest"
    (gdb)
    Now the essence of that is what I posted, but now you know how I got there.
    and you are even jumping on the band wagon and doing the same thing the others are doing, testing something that was put there AFTER the fact, do you and the two others even understand what "after the fact' even means?

    I never argued the printing out like I did may be the cause of a seg fault, I argued that the printf in main, being accused of causing the seg fault where not the real reason because they were put there after the fact.


    it should have prompted you and every one else to look else where for an offending whatever it maybe that is causing it to seg fault, instead of keep leadning me back to the printf in main, that could in no way have caused the seg fault in the first place.

    having another set of eyes on it is not a bad thing. the ears attached to the same head that does not listen to what took place instead it just keeps looking where it should not be looking is not a good thing.

    good night sir's and hot head with a foul mouth.
    Last edited by poorboy; 11-29-2018 at 07:34 AM.

  15. #30
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,657
    So where exactly did you post any evidence that you saw an "after malloc" and then a segfault?

    Code:
      printf("before malloc %s\n", path);
        
      //segfaults here
        
      names = (char **)malloc(sum * sizeof(char *));
     
      if (names == NULL)
      {
          printf("Names is NULL\n");
      }
      printf("after malloc %s %s\n", path,*names);
    > it should have prompted you and every one else to look else where for an offending whatever it maybe that is causing it to seg fault
    What are you on about?

    It was plainly obvious to me even at post #2 that the "after malloc" printf was going to be accessing garbage data and a prime candidate for failure.
    Even at post #28 with direct evidence from the debugger that the offending line is that "after malloc" printf, you seem to be trying to divert blame somewhere else.

    malloc itself can segfault, but that's only usually the result of prior abuse of the dynamic memory pool by some earlier code. As this was the first call in your code, the chance of this being the cause was minimal.

    Believing that printf was never called prior to the segfault is an erroneous assumption on your part.
    There is absolutely NO reason at all why you might see
    Code:
    after malloc /media/data1/TEST Segmentation fault (core dumped)
    Yes, some implementations may literally output the printf string one character at a time, and only crash on attempting to convert the second %s.
    By the same token, other implementations may choose to format the whole thing using snprintf, and then print the whole formatted string. These would crash long before you ever saw the first character.
    Both are valid, but there should be no expectation on your part that one is necessary or preferred over the other.

    Your use of calloc just sweeps the problem under the rug, because your (and my) particular implementation of printf with %s and a NULL pointer gives a nice little message to nudge you in the right direction, as opposed to an in your face segfault. That doesn't make your code any less wrong.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 04-02-2014, 05:29 PM
  2. Replies: 9
    Last Post: 11-18-2008, 02:59 AM
  3. Replies: 3
    Last Post: 11-17-2008, 12:36 PM
  4. Replies: 5
    Last Post: 12-22-2005, 06:50 PM
  5. How to malloc (char **)
    By Stack Overflow in forum C Programming
    Replies: 2
    Last Post: 05-06-2004, 07:24 PM

Tags for this Thread