Find the answer to your Linux question:
Results 1 to 3 of 3
Something has happened which I've never seen before: a segfault inside a C library function. And I do mean a segfault, not one of those diagnostic aborts due to detected ...
  1. #1
    Linux Engineer hazel's Avatar
    Join Date
    May 2004
    Location
    Harrow, UK
    Posts
    955

    What (if anything) is wrong with this code?

    Something has happened which I've never seen before: a segfault inside a C library function. And I do mean a segfault, not one of those diagnostic aborts due to detected corruption.

    Here is the code:
    Code:
    DIR *directory;
    	char *trash, *trash_files;
    	...
    	trash = find_trash ();
    	trash_files = (char *)g_malloc (strlen(trash)+8);
    	
    	trash_files = strcat (trash, "/files");
    
    printf ("%s\n", trash_files);
    printf ("About to run opendir\n");
    	directory = opendir (trash_files);
    printf ("Opendir complete\n");
    The printf statements are for diagnosis only; the first checks that the returned directory name which will be passed to opendir is what it ought to be, the other two bracket the opendir command and confirm that this is where the crash occurs. The first prints, the second doesn't.

    But the really weird thing is that if I run this through valgrind rather than directly, it doesn't crash and appears to behave normally.

    Has anybody met this sort of behaviour before?
    "I'm just a little old lady; don't try to dazzle me with jargon!"

  2. #2
    Linux Newbie
    Join Date
    Dec 2009
    Posts
    241
    To tell you the truth ... I've no idea ...
    you may just try:
    Code:
    trash_files = strcat (trash, "/files");
    trash_files = strcat (trash_files, 0);
    Just to make sure, that trash_files ends after "files".
    0 should mark end of string

  3. #3
    Linux Engineer hazel's Avatar
    Join Date
    May 2004
    Location
    Harrow, UK
    Posts
    955
    Good thinking! That wasn't in fact the error but it turned out to be an error of that kind. The problem was actually in the get_trash function, where an allocated buffer was just one character too short, so a terminating null got lost. That error must have propagated itself through strcat(); I don't know how strcat() actually works but, as the printed directory name looked OK, my guess is that a reasonable assumption was made about the presence of a proper null terminator and that led to an invisible binary character being included in the pathname, which was what crashed opendir().

    I forgot one of the most basic rules of debugging, which is that a statement which crashes your program is not necessarily the location of the fatal error; it may just expose an error which occurred elsewhere.
    "I'm just a little old lady; don't try to dazzle me with jargon!"

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...