Need help with segmentation fault

This is a discussion on Need help with segmentation fault within the C Programming forums, part of the General Programming Boards category; so,here´s my problem:i have a function that should order an array by the size of the words that compose it.The ...

  1. #1
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82

    Need help with segmentation fault

    so,here´s my problem:i have a function that should order an array by the size of the words that compose it.The array is declared as **text,and has strings in each position.The problem is that i´m having a segmentation fault and cant solve it.i post here the fucntion so that someone can help me:
    Code:
    void ordena_histograma(char **texto,int num,int i)
    {
    	int n=0,u=0,j;
    	char *temp;
    	if(i == (num-1))
    		;
    	else 
    	{
    		n=strlen(texto[i]);
    		u=strlen(texto[i+1]);
    		if(n<=u)
    			ordena_histograma(texto, num, i+1);
    		else
    			{
    				temp=(char *)malloc (n);
    				*temp=*(texto[i]);
    				texto[i]=texto[i+1];
    				texto[i+1]=temp;
    				ordena_histograma(texto,num,i+1);
    			}
    	}
    }

  2. #2
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82

    Unhappy

    Still having a problem with segmentation fault...here´s my program code.the idea is to write a program that reads words from an imput text and prints the number of ocurrences of each word,alphabetcly ordered,and the number of words with the same size,ordered from the smallest size to the largest.My program does everything ok,except ordering things...It reads the words from the file and stores each of them in an array position(texto).The problem is that i use structures list to store the words,an before inserting the words in each list(one for the size,another for the ocorrences of each word),i have to order the words in the array,according to each parameter...Hope someone can help me.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    /* Definicao do tipo ocorrencia */
    typedef struct as_ocorrencias
    {
    	int num_ocorrencias;
    	char *palavra;
    	struct as_ocorrencias *proximo;
    } OCORRENCIAS;
    
    typedef struct o_histograma
    {
    	int num_vezes;
    	int tamanho;
    	struct o_histograma *proximo;
    } HISTOGRAMA;
    
    typedef OCORRENCIAS* ocorrencias;
    typedef HISTOGRAMA* histograma;
    
    int ja_existe_ocorrencia(char *palavra, ocorrencias* Ocorrencias, int n)
    {
    	if(*Ocorrencias== NULL)
    		return n;
    	else
    	{
    		if(strcmp(palavra, (*Ocorrencias)->palavra))
    			n=n + (ja_existe_ocorrencia(palavra, &(**Ocorrencias).proximo, n));
    		else
    		{
    			(*Ocorrencias)->num_ocorrencias +=1;
    			n+=1;
    		}
    	}
    	return n;
    }
    int ja_existe_histograma(int tamanho, histograma* Histograma, int n)
    {
    	if(*Histograma== NULL)
    		return n;
    	else
    	{
    		if(tamanho== (*Histograma)->tamanho)
    		{
    			(*Histograma)->num_vezes+=1;
    			n+=1;
    		}
    		else
    			n=n + (ja_existe_histograma(tamanho, &(**Histograma).proximo, n));
    	}
    	return n;
    }
    /* Inicia a ocorrencia*/
    void inicia_ocorrencias(ocorrencias* Ocorrencias)
    {
    	*Ocorrencias = NULL;
    }
    /* Inicia o histograma*/
    void inicia_histograma(histograma* Histograma)
    {
    	*Histograma = NULL;
    }
    void acrescentaux_ocorrencias (ocorrencias* Ocorrencias, int num_ocorrencias, char *palavra,int n)
    {
    	if(*Ocorrencias == NULL)
    		{
    			*Ocorrencias=(ocorrencias)malloc(sizeof(OCORRENCIAS));
    			if(*Ocorrencias == NULL)
    				return;
    				(*Ocorrencias) -> num_ocorrencias=num_ocorrencias;
    				(*Ocorrencias) -> palavra=malloc (n);
    				strcpy ((*Ocorrencias) -> palavra, palavra);
    				(**Ocorrencias).proximo = NULL;
    		}
    		else
    			acrescentaux_ocorrencias(&(**Ocorrencias).proximo, num_ocorrencias, palavra,n);
    }
    void acrescentaux_histograma (histograma* Histograma, int num_vezes, int tamanho)
    {
    	if(*Histograma == NULL)
    		{
    			*Histograma=(histograma)malloc(sizeof(HISTOGRAMA));
    			if(*Histograma == NULL)
    				return;
    				(*Histograma) -> num_vezes=num_vezes;
    				(*Histograma) -> tamanho=tamanho;
    				(**Histograma).proximo = NULL;
    		}
    		else
    			acrescentaux_histograma(&(**Histograma).proximo, num_vezes, tamanho);
    }
    /* Insere uma nova ocorrencia*/
    void acrescenta_ocorrencias (ocorrencias* Ocorrencias, int num_ocorrencias, char *palavra,int n)
    {
    		if((ja_existe_ocorrencia(palavra, Ocorrencias, 0))==0)
    		acrescentaux_ocorrencias(Ocorrencias, num_ocorrencias, palavra,n);
    }
    /* Insere um novo histograma*/
    void acrescenta_histograma (histograma* Histograma, int num_vezes, int tamanho)
    {
    		if((ja_existe_histograma(tamanho, Histograma, 0))==0)
    		acrescentaux_histograma(Histograma, num_vezes, tamanho);
    }
    
    void escreve_ocorrencias(ocorrencias Ocorrencias)
    {
    	if(Ocorrencias == NULL)
    		return;
    	printf("%s %d\n", Ocorrencias -> palavra, Ocorrencias -> num_ocorrencias);
    	escreve_ocorrencias(Ocorrencias -> proximo);
    }
    void escreve_histograma(histograma Histograma)
    {
    	if(Histograma == NULL)
    		return;
    	printf("%d %d\n", Histograma -> tamanho, Histograma -> num_vezes);
    	escreve_histograma(Histograma -> proximo);
    }
    
    
    char *limpa_palavra(char palavra[])
    {
    	int ui;
    	for(ui=0; ui<(strlen(palavra));ui++)
    		palavra[ui]=' ';
    	return palavra;
    }
    
    	
    int compare ( const void *a, const void *b ) 
    {
        const char **pa ;
        const char **pb ;
        size_t  la = strlen( *pa );
        size_t  lb = strlen( *pb );
        if ( la < lb ) return -1;
        if ( la > lb ) return +1;
        return 0;
    }
    
    
    main(int argc, char *argv[])
    {
    	FILE *fp;
    	char palavra[BUFSIZ];
    	char texto [BUFSIZ][BUFSIZ];
    	char c;
    	int i=0;
    	int conta_palavras=0;
    	int p;
    	ocorrencias oc;
    	histograma h;
    	inicia_ocorrencias(&oc);
    	inicia_histograma(&h);
    	fp = fopen(argv[1],"r");
    	if(argc != 2)
    	{
    		printf("Numero de argumentos invalidos\n");
    		exit(0);
    	}
    		else
    	{
    		if(fp == NULL)
    		{
    			printf("Impossivel abrir o ficheiro %s\n",argv[1]);
    			exit(1);
    		}
    		else
    		{
    			while ((c=fgetc(fp))!=EOF)
    			{
    				if(i==0)
    				{
    					if ( c==95 || c>64 && c<91 || c>96 && c<123)
    					{
    						palavra[i]=c;
    						++i;
    					}
    					else continue;
    				}
    				else 
    			{
    				if(c<58 && c>47 || c>64 && c<91 || c>96 && c<123 ||c==95 )
    				{
    					palavra[i]=c;
    					++i;
    				}
    				else
    				{
    					palavra[i]='\0';
    					strcpy(*(texto+conta_palavras),palavra);
    					conta_palavras=++conta_palavras;
    					i=0;
    					limpa_palavra(palavra);
    				}
    			}
    			
    			}
    			palavra[i]='\0';
    					strcpy(*(texto+conta_palavras),palavra);
    					conta_palavras=++conta_palavras;
    					i=0;
    					limpa_palavra(palavra);
    	}
    	}
        for(p=0;p< conta_palavras;++p)
        {
        	acrescenta_ocorrencias(&oc, 1, texto[p],strlen(texto[p]));
        	acrescenta_histograma(&h, 1, strlen(texto[p]));
        }
        qsort(texto,sizeof(texto)/sizeof(texto[0]),sizeof(texto[0]),compare);
    	printf("TOTAL: %d\n", conta_palavras);
    	puts("HISTOGRAMA:");
    	escreve_histograma(h);
    	putchar('\n');
    	puts("OCORRENCIAS:");
    	escreve_ocorrencias(oc);
    }

  3. #3
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82
    I´m sorry if i wasnt supposed to post all the code here.I just need to know how to use the qsort function correctly.I only have 2 days left to finish the project,so please hurry if anyone knows how to help!

  4. #4
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82
    I altered the qsort function u gave me,because i was having a segmentation fault:
    Code:
    int compare ( char *a, char *b ) 
    {
        int la=strlen(a);
        int lb=strlen(b);
        if ( la < lb ) return -1;
        if ( la > lb ) return +1;
        return 0;
    
    }
    And i´m calling qsort like this:
    Code:
    qsort(texto, sizeof(texto)/sizeof(texto[0]),sizeof(texto[0]),compare);
    I end up with an array with empty words in each position!whats wrong?

  5. #5
    Registered User Vber's Avatar
    Join Date
    Nov 2002
    Posts
    807
    For comparing strings with qsort, look this example:
    Code:
    include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* some_strs[] = { "last", "middle", "first" };
    
    int compare( const void* op1, const void* op2 )
    {
        const char **p1 = (const char **) op1;
        const char **p2 = (const char **) op2;
    
        return( strcmp( *p1, *p2 ) );
    }
    
    int main( void )
    {
        qsort( some_strs,
               sizeof( some_strs ) / sizeof( char * ),
               sizeof(char *),
               compare );
    
        printf( "%s %s %s\n",
            some_strs[0], some_strs[1], some_strs[2] );
            
        return EXIT_SUCCESS;
    }

  6. #6
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82
    Ok,so i managed to order the string in the array.Now i´m having another problem:i tested "this a text" to see if the program works.In the end,i should get this result:
    Histogram:
    1 1
    2 1
    4 2

    Words:
    a
    is
    text
    this

    The problem is i get this result:
    Histogram:
    1 2
    2 1
    4 3

    Words:
    a
    @
    is
    text
    asd.w
    this

    Then i tried a printf in each array position,after ordering it,and the strings asd.w and @ are really there,despite not being in the original text!Can someone help me?they werent supposed to be there!

  7. #7
    Registered User Lost__Soul's Avatar
    Join Date
    Mar 2003
    Posts
    82
    Well,no need for help now,its working fine,i corrected all errors,thnks for the help everyone gave me!Now i only need to replace the BUFSIZ thing,since the arrays arent supposed to have size limits.But thats easy,i think,Thnks again!

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Originally posted by Lost__Soul
    Well,no need for help now,its working fine,i corrected all errors,thnks for the help everyone gave me!Now i only need to replace the BUFSIZ thing,since the arrays arent supposed to have size limits.But thats easy,i think,Thnks again!
    Before you ask, read this
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Segmentation fault problem
    By odedbobi in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2008, 03:36 AM
  2. Segmentation fault
    By bennyandthejets in forum C++ Programming
    Replies: 7
    Last Post: 09-07-2005, 06:04 PM
  3. Segmentation fault
    By NoUse in forum C Programming
    Replies: 4
    Last Post: 03-26-2005, 03:29 PM
  4. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 01:33 PM
  5. Segmentation fault...
    By alvifarooq in forum C++ Programming
    Replies: 14
    Last Post: 09-26-2004, 01:53 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21