Segmentation fault in fopen when in write mode.


 
Thread Tools Search this Thread
Top Forums Programming Segmentation fault in fopen when in write mode.
# 8  
Old 07-17-2012
In what way does it fail to execute, though?
# 9  
Old 07-17-2012
The same old segmentation fault message:

Code:
Program received signal SIGSEGV, Segmentation fault.
0x00000031f4a7873e in _int_malloc () from /lib64/libc.so.6

# 10  
Old 07-17-2012
Unless I missed something, all of the following code can be replaced with two snprintf (or sprintf) calls. (It probably has nothing to do with your segfault, but needless complexity never helps.)

Quote:
Originally Posted by shoaibjameel123
Code:
void file_names ( unsigned int i , char * file_name , char * str )
{
    char common_path[] = {"/data/scores/"};

    str = itoa ( i  , str );
    strcat ( file_name , common_path );
    strcat ( str , ".dat" );
    strcat ( file_name , str );
}


void file_name_generator ( unsigned long int i , char * file_name , char *str )
{
    strcat ( file_name , "/data/files/" );
    str = itoa ( i , str );
    strcat ( file_name, str );
    strcat ( file_name , ".dat" );
}


char * itoa ( int n , char * s )
{
     int i, sign;
 
     if ( ( sign = n ) < 0 )  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s [ i++ ] = n % 10 + '0';   /* get next digit */
     } while ( ( n /= 10 ) > 0 );     /* delete it */
     if ( sign < 0 )
         s [ i++ ] = '-';
     s [ i ] = '\0';
     reverse ( s );
    return ( s );
}


char * reverse ( char s [ ] )
{
     int i, j;
     char c;
 
    for ( i = 0, j = strlen ( s ) - 1; i < j; i ++, j -- ) 
    {
             c = s [ i ];
             s [ i ] = s [ j ];
             s [ j ] = c;
         }
    return ( s );
}

Regards,
Alister

---------- Post updated at 12:26 AM ---------- Previous update was at 12:10 AM ----------

I haven't tried to compile your code, just looking it over, but the following is wrong:
Code:
str = ( char * ) malloc ( 4 * sizeof ( char ) );

void file_names ( unsigned int i , char * file_name , char * str )
{
    char common_path[] = {"/data/scores/"};

    str = itoa ( i  , str );
    strcat ( file_name , common_path );
    strcat ( str , ".dat" );
    strcat ( file_name , str );
}

str doesn't even have enough room for ".dat", which requires 5 bytes.

Regards,
Alister

Last edited by alister; 07-17-2012 at 01:38 AM..
# 11  
Old 07-17-2012
Great solved the problem:

This is what I did. Put this piece of code
Code:
fclose ( input_file );

Like this:
Code:
        while ( !feof ( input_file ) )
        {
            while ( ( read = getline ( &line , &len , input_file ) ) != -1 )
            {
                line = chomp ( line );
                strcpy ( words_from_webpage [ j ] , line );
                if ( j <= number_of_words )
                {
                    j ++;
                }
            }
        }
        
        fclose ( input_file );

And BINGO!!! it worked Smilie

Also, thanks Alister, yes that was my mistake. I have increased the size of str. But there now I have encountered another problem.

When the following section comes:

Code:
while ( j < number_of_words )
        {
            fprintf ( output_pointer , "%ld\n" , store_values [ j ]);
            j ++;
        }
fclose ( output_pointer );

The program now faults again.
Code:
*** glibc detected *** /data/compute_scores.out: free(): corrupted unsorted chunks: 0x000000001d6ed3b0 ***

Program received signal SIGSEGV, Segmentation fault.
0x00000031f4a7873e in _int_malloc () from /lib64/libc.so.6

This happens when I go to the next line after
Code:
fclose ( output_pointer );

in gdb

---------- Post updated at 12:42 PM ---------- Previous update was at 12:39 PM ----------

Now the problem does not occur with
Code:
output_pointer = fopen ( file_name , "w" );

but with
Code:
fclose ( output_pointer );

---------- Post updated at 02:43 PM ---------- Previous update was at 12:42 PM ----------

Finally the problem has been solved and the program is executing perfectly. I have made one change in the program.

Take out all malloc() calls inside this for loop and initialize them outside the loop.
Code:
for ( i = 0 ; i < NUMBER_OF_FILES ; i ++ )

After placing the following statements outside, the code runs well.

Code:
store_values = ( unsigned long int * ) malloc ( number_of_words * sizeof ( unsigned long int ) ); this array will store all the numerical values corresponding to the words
        if ( store_values == NULL )
        {
            fprintf ( stderr , "malloc() memory allocation failure\n" );
        }

        words_from_webpage = ( char ** ) malloc ( number_of_words * sizeof ( char * ) ); //this read the data file consising of words each word in newline
        if ( words_from_webpage == NULL )
        {
            fprintf ( stderr , "malloc() memory allocation failure in words_from_webpage\n" );
        }

        for ( j = 0 ; j < number_of_words ; j ++ )
        {
            words_from_webpage [ j ] = ( char * ) malloc ( 20 * sizeof ( char ) );
            if ( words_from_webpage [ j ] == NULL )
            {
                fprintf ( stderr , "malloc() memory allocation failure\n" );
            }
        }

But now I have to pre-define the value of
Code:
number_of_words

. SO, I used #define preprocessor declaration and hard coded this value.

I am not sure why allocation of memory inside the for loop did not work.
# 12  
Old 07-17-2012
That loop is leaking memory badly. Each time store_values and words_from_webpage are assigned a pointer, the only references to the un-free()'d memory allocated during the previous iteration are lost.

Perhaps there are other problems, but I just focused on what you highlighted in your most recent post.

Why are you using C for this? A learning exercise? If so, great. If not, consider using awk, perl, python, or something else that operates at a higher level. You're not gaining much by using C for this and you are wasting a lot of time with the memory management bugs. If it must be C, you'll probably benefit from using static analysis tools (valgrind, for example).

Also, consider that there's no reason (other than educational) to bother with itoa(), reverse(), and the string generating functions that they are supporting. snprintf() will do everything that they are doing.

Regards,
Alister

Last edited by alister; 07-17-2012 at 11:38 AM..
This User Gave Thanks to alister For This Post:
# 13  
Old 07-17-2012
Yes, in the loop things were not perfect and memory leak was excessive. I've fixed some of the other problems too, but those are minor.

There are some reasons why I use C for everything. One is that I work on extremely large sets of text files and do mathematical computations using those files. Hence, efficiency is one reason. But indeed I do have to toil extra hard to get my code perfect.

snprintf() is a valid suggestion and can get my code a lot more compact and readable. Thanks for that. I'll use it in my future codes.

One big reason why I stick to C is "passion". Just like some people love climbing Mount Everest but others think that they are wasting their precious time and life. (The last sentence is just a joke Smilie).
# 14  
Old 07-17-2012
Quote:
Originally Posted by shoaibjameel123
One big reason why I stick to C is "passion".
Understood. Smilie

Regards,
Alister
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

C. To segmentation fault or not to segmentation fault, that is the question.

Oddities with gcc, 2.95.3 for the AMIGA and 4.2.1 for MY current OSX 10.14.1... I am creating a basic calculator for the AMIGA ADE *NIX emulator in C as it does not have one. Below are two very condensed snippets of which I have added the results inside the each code section. IMPORTANT!... (11 Replies)
Discussion started by: wisecracker
11 Replies

2. Shell Programming and Scripting

Count Segmentation fault and write to the file

Hi everyone Need to get version of npm application that have several output like this: root: nmp -version 10 root: nmp -version 10 root: nmp-new -version 3.1 root: nmp-old -version Segmentation fault count them , after that write to the file like this: 10 2 3.1 1 (1 Reply)
Discussion started by: indeed_1
1 Replies

3. Solaris

Segmentation fault

Hi Guys, I just installed and booted a zone called testzone. When I logged in remotely and tried changing to root user I get this error: "Segmentation fault" Can someone please help me resolve this? Thanks alot (2 Replies)
Discussion started by: cjashu
2 Replies

4. Programming

Using gdb, ignore beginning segmentation fault until reproduce environment segmentation fault

I use a binary name (ie polo) it gets some parameter , so for debugging normally i do this : i wrote script for watchdog my app (polo) and check every second if it's not running then start it , the problem is , if my app , remain in state of segmentation fault for a while (ie 15 ... (6 Replies)
Discussion started by: pooyair
6 Replies

5. UNIX for Dummies Questions & Answers

Segmentation fault

#include<stdio.h> #include<malloc.h> #include<unistd.h> #include<stdlib.h> void *start_1(void *argv) { printf("thread 0x%x\n",(unsigned int)pthread_self()); pthread_exit((void*)1); } void *start_2(void *argv) { printf("thread 0x%x\n",(unsigned int)pthread_self()); return (void*)2; }... (2 Replies)
Discussion started by: vincent__tse
2 Replies

6. Programming

Segmentation fault.

I'm getting a segmentation fault. I'm new to Linux programming. Thanks so much for all of your input.:eek: #include </usr/include/mysql++/mysql++.h> #include <stdio.h> #include <iostream> #include <sstream> #include <string.h> using namespace std; int outputToImport(const char*... (1 Reply)
Discussion started by: sepoto
1 Replies

7. Programming

segmentation fault

Hi, I am having this segmentation fault not in the following program, bt. in my lab program . My lab program is horrible long so cannot post it here bt. I am using the following logic in my program which is giving the segmentation fault. Bt. if I run this sample program as it is it dosen't give... (3 Replies)
Discussion started by: mind@work
3 Replies

8. AIX

Segmentation fault

Hi , During execution a backup binary i get following error "Program error 11 (Segmentation fault), saving core file in '/usr/datatools" Riyaz (2 Replies)
Discussion started by: rshaikh
2 Replies

9. Programming

Hi! segmentation fault

I have written a program which takes a directory as command line arguments and displays all the dir and files in it. I don't know why I have a problem with the /etc directory.It displays all the directories and files untill it reaches a sub directory called peers which is in /etc/ppp/peers.the... (4 Replies)
Discussion started by: vijlak
4 Replies

10. Programming

segmentation fault

sometimes for this code i get a segmentation fault for codes llike this : int main{ int * a= 0; int b; a = (int*)malloc(sizeof(int)); ///some code using these variable but no freeing of a if(a){ free(a); a = 0; } return... (3 Replies)
Discussion started by: wojtyla
3 Replies
Login or Register to Ask a Question