Thread: Random from dynamic memory allocation

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    159

    Random from dynamic memory allocation

    Hi

    I have this code, can someone tell me if there is anything wrong with that??

    Code:
    void gp1_Ques(struct perg *p)
    {
    char * lista[200]; // mil perguntas com tamanho mximo de 255 caracteres
    char *copia;
    int count, random;
    FILE *f;
    if ((f = fopen("gp1.dat", "rb")) == NULL)
    {
      printf("Erro ao abrir ficheiro\n");
    }
    else
    {
      count = 0;
      while (fgets(lista[count], 200, f) == lista[count])
      {
    copia=malloc(sizeof *lista[count]);
       count++;
      }
      // fechar ficheiro
      fclose(f);
      //escolher pergunta
      random=rand() % count;
    }
    for (i=0; i <count-1; i++)
    {
    printf("%s\n",lista[random]);
      free(copia);
    }
    }

    Well new data

    iv'e got this using debuger

    Program received signal SIGSEGV, segmentation fault

    copia = 0x4050a3"%d"
    i = 1976527024
    random = 1976527113
    count = 0
    f = 0x75d22960

    with this line

    while (fgets(lista[count], 200, f) == lista[count])


    Any help?
    Last edited by Gil Carvalho; 05-22-2012 at 12:50 PM. Reason: mode data

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    I'm looking at your post count, and wondering why your code is still an eyesore to look at.

    Look at this
    Code:
    int main ( ) {
        // do some stuff
        printf("tada!!!");
        return 0;
    }
    Look at your code


    Now back to this
    Code:
    int main ( ) {
        // do some stuff
        printf("tada!!!");
        return 0;
    }
    Do you see
    - fixed pitch fonts
    - line numbers
    - syntax colouring
    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.

  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Let me try now.

    Code:
    void gp1_Ques(struct perg *p)
    {
    	char * lista[200]; // mil perguntas com tamanho mximo de 255 caracteres
    	char *copia;
    	int count, random, i;
    	FILE *f;
    	if ((f = fopen("gp1.dat", "rb")) == NULL)
    	{
    		printf("Erro ao abrir ficheiro\n");
    	}
    	else
    	{
    		count = 0;
    		while (fgets(lista[count], 200, f) == lista[count])
    		{
    			copia=malloc(sizeof *lista[count]);
    			count++;
    		}
    		// fechar ficheiro
    		fclose(f);
    		//escolher pergunta
    		random=rand() % count;
    	}
    	for (i=0; i <count-1; i++)
    	{
    		printf("%s\n",lista[random]);
    		free(copia);
    	}
    }

  4. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Google translates the comment on line 3 as: "thousand questions with a maximum length of 255 characters". I have no idea where you think 255 comes from.

    Your bugs are on lines: 14, 16, 24, and presumably line 26 isn't what you want either.

    You have to allocate room to store some text, before you try and read it in. Allocating more than one character would help too.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  5. #5
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi,
    Thanks

    You have to allocate room to store some text, before you try and read it in
    Excuse me but i don't know how to do it.

    Can you tell me how please?

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well normally, you would read lines from a file like so
    Code:
    #define MAX_LINES 200
    char * lista[MAX_LINES];
    char buff[BUFSIZ]; // BUFSIZ is in stdio.h
    int count = 0;
    while ( count < MAX_LINES &&
            fgets(buff,BUFSIZ,f) != NULL ) {
        // trim the newline from buff - if you need to, see the FAQ
        // work out the length of buff
        // allocate that much space using malloc, store the pointer in lista[count]
        // copy from buff to your allocated memory
        // increment the count
    }
    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.

  7. #7
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi

    I used like this:

    Code:
    void gp1_Ques(struct perg *p)
    {
      char * lista[100];  // 100 perguntas, o tamanho de cada no  especificado aqui
      int count, random, i;
      FILE *f;
      if ((f = fopen("gp1.dat", "rb")) == NULL)
      {
            printf("Erro ao abrir ficheiro\n");
      }
      else
      {  
            for (count = 0;; count++)
            {
              lista[count] = malloc(200);
              if (fgets(lista[count], 200, f) == NULL)
              {
                    free(lista[count]);
                    break;
              }
            }
            // fechar ficheiro
            fclose(f);
            // escolher pergunta
            random=rand() % count;
            printf("%s\n",lista[random]);
            for (i=0; i < count; i++)
            {
              free(lista[i]);
            }
      }
    What do you think?

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    I think you need to limit count to the number of elements in your lista array.
    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.

  9. #9
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Quote Originally Posted by Salem View Post
    I think you need to limit count to the number of elements in your lista array.
    Instead of 200 i must 100 like lista array has?

    Thnaks

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > Instead of 200 i must 100 like lista array has?
    Your point being?

    Did you not figure that you could change
    #define MAX_LINES 200
    into
    #define MAX_LINES 100
    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.

  11. #11
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Already did it Salem

    Thank you for your help.

    Best regards

  12. #12
    Registered User
    Join Date
    Apr 2012
    Posts
    159
    Hi all

    I thought this was ok since i had no errors but when i'm running the function nothing goes like i want.

    Code:
    void gp1_Ques(struct perg *p)
    {
        #define MAX_LINES 250
        char * lista[MAX_LINES];
        char buff[BUFSIZ]; // BUFSIZ is in stdio.h
        int count = 0;
        int i, random;
        FILE *f;
        if ((f = fopen("gp1.dat", "rb")) == NULL)
        {
            printf("Erro ao abrir ficheiro\n");
        }
        else
        {
            for (count = 0;; count++)
            {
              lista[count] = malloc(250);
              if (fgets(lista[count], 250, f) == NULL)
              {
                    free(lista[count]);
                    break;
              }
            }
        }
            // fechar ficheiro
            fclose(f);
            // escolher pergunta
            random=rand() % count;
            printf("Count %d  and random %d",count, random);
            printf("%s\n",lista[random]);
            for (i=0; i < count; i++)
            {
              free(lista[i]);
            }
    }
    Well, the function works until
    printf("Count %d and random %d",count, random);

    Doesn't give me the list, and the numbers from count is 242 and random last time was 41.

    The count is wrong since i have only 20 records, so i think that 242 is the characters from the file. (binary file)

    My file is the following

    O que se come no Sao Martinho?
     ݯM4 `@` t4  kH4 qO4
    p
    @ Nozes
     5Castanhas
    Natas
    j4 Chourico
    Os rojoes tipicos são moda do...
     ݯM4 `@` t4  kH4 qO4
    p
    @ Porto
     5Alentejo
    Minho
    j4 Douro
    o
    Quem e o actual presidente do Patido Socialista (PS)?
    ݯM4 `@` t4  kH4 qO4
    p
    @ Soares
     5Socrates
    Seguro
    4 Cavaco

    Qual a capital das Filipinas?
    atido Socialista (PS)?
    ݯM4 `@` t4  kH4 qO4
    p
    @ Manila
     5Banguecoque
    Seoul
    4 Pequim

    Qual a capital de Cuba?
    nas?
    atido Socialista (PS)?
    ݯM4 `@` t4  kH4 qO4
    p
    @ Bayamo
     5Santa Clara
    Las Tunas
     Havana

    Quem foi o realizador do filme "Gladiador"?
    ta (PS)?
    ݯM4 `@` t4  kH4 qO4
    p
    @ James Cameron
    Peter Jackson
    R.Zemeckis
    ki Ridley Scott
    Quantas Taças de Portugal já conquistou o S.L. Benfica?
    ݯM4 `@` t4  kH4 qO4
    p
    @ 19
    s Cameron
    12
    r Jackson
    24
    meckis
    ki 26
    ey Scott
    Quem venceu o Campeonato do Mundo, disputado na Argentina, em 1978?
    M4 `@` t4  kH4 qO4
    p
    @ Brasil
    meron
    Inglaterra
    n
    Argentina
    ki Alemanha
    tt
    Em que ano foi fundada a NASA?
    o, disputado na Argentina, em 1978?
    M4 `@` t4  kH4 qO4
    p
    @ 1955

    meron
    1956
    erra
    n
    1957
    ina
    ki 1958
    ha
    tt

    Mozart era?
    i fundada a NASA?
    o, disputado na Argentina, em 1978?
    M4 `@` t4  kH4 qO4
    p
    @ Hungaro
    eron
    Alemao
    ra
    n
    Austriaco
    ki Portugues
    t
    Que actriz foi galardoada com o Óscar de melhor actriz em 2000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ Hillary Swank
    Halle Barry

    C. Theron
    ron Julia Roberts
    Cor predominante da Bandeira da Áustria?
    elhor actriz em 2000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ Laranja
    wank
    Vermelho
    y

    Azul
    ron
    ron Verde
    oberts

    Numero pertencente a sequaencia 2, 4, 8, 16, 18, 32, 64...
    000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ 254
    ja
    wank
    2046
    ho
    y

    132
    ron
    ron 4096
    oberts
    O mesmo que setentrional?
    ncia 2, 4, 8, 16, 18, 32, 64...
    000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ Norte

    wank
    Sul
    ho
    y

    Leste
    on
    ron Oeste
    oberts
    O numero 101 em romanos?
    ncia 2, 4, 8, 16, 18, 32, 64...
    000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ CI
    e

    wank
    MI
    ho
    y

    DI
    e
    on
    ron EI
    e
    oberts
    O Aeroporto Internacional Orly situa-se em
    18, 32, 64...
    000?
    ?
    M4 `@` t4  kH4 qO4
    p
    @ Alemanha
    ank
    Espanha
    y

    Franca
    n
    ron Italia
    berts
    Antes de embarcar num voo qualquer, qual é o procedimento que tem de seguir?
    `@` t4  kH4 qO4
    p
    @ Check saude

    Check dentes
    Check out
    ron Check in
    rts
    Qual destes pa..ses não pertence ao continente Europeu?
    que tem de seguir?
    `@` t4  kH4 qO4
    p
    @ Portugal
    e

    Marrocos
    es
    Espanha

    ron Lituania
    rts
    Qual a serra mais alta de Portugal?
    continente Europeu?
    que tem de seguir?
    `@` t4  kH4 qO4
    p
    @ Marao
    l
    e

    Serra Estrela
    Caldeirao
    ron Arrabida
    rts
    Onde nasce o rio Tejo
    de Portugal?
    continente Europeu?
    que tem de seguir?
    `@` t4  kH4 qO4
    p
    @ Franca

    e

    Alemanha
    ela
    Portugal
    ron Espanha
    rts
    Anyone knows whats wrong with this code??

    Thanks

  13. #13
    Registered User
    Join Date
    Mar 2012
    Location
    the c - side
    Posts
    373
    Judging by the size of your file the 242 would probably refer to the number of LINES, which is what your program is reading. The file, btw, as you have presented it, is corrupt anyway so may not be usable. Line 41 seems to coincide with a blank line which would give you seemingly nothing. In order for your program to work the way you want, you would need to think about reading and storing in a more sophisticated manner, perhaps reading and storing each record as a structure?

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    That file is totally unsuitable for reading using fgets

    If this is a continuation of your previous question and answers thread, then you NEED to use the same structure and then use fread(), as you used to fwrite() the file to begin with.

    Your char *lista[MAX] would need to be struct perg *lista[MAX]
    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.

  15. #15
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by Gil Carvalho View Post
    I thought this was ok since i had no errors but when i'm running the function nothing goes like i want.
    Code compiling without errors (and warnings hopefully) is no guarantee that it does what you want! It just means you don't have any compiler errors (or warnings)
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Memory Allocation
    By slash.hack in forum C Programming
    Replies: 9
    Last Post: 09-30-2011, 04:31 AM
  2. what is dynamic memory allocation
    By dbzx in forum C Programming
    Replies: 7
    Last Post: 06-08-2009, 08:11 AM
  3. Dynamic Memory Allocation
    By BoneXXX in forum C Programming
    Replies: 11
    Last Post: 03-26-2007, 01:43 AM
  4. Dynamic memory allocation.
    By HAssan in forum C Programming
    Replies: 3
    Last Post: 09-07-2006, 05:04 PM
  5. dynamic memory allocation
    By inquisitive in forum C++ Programming
    Replies: 5
    Last Post: 03-13-2004, 02:07 AM