Thread: a problem we couldnt fix...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    10

    a problem we couldnt fix...

    Code:
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>
    char* saisit_chaine_sans_tampon()
    {
           int i,s;
           char *q;
           printf("Ecrivez une chaine de caractere-Pour sortir touche '1'");
           (char*)realloc(q,(1*sizeof(char)));
           *q='a';//je donne une valeur initialement,sinon il y une errruer
           for(i=0;q[i-1]!='1';i++)
           {
                                  q[i]=getch();
                                  s=i+1;
                                  (char*)realloc(q,(s*sizeof(char)));
    
                                  }
                                  q[i-1]='\0';
                                  return q;
                                  free(q);
    }
    
    int main()
    {
        char *p;
        p=saisit_chaine_sans_tampon();
        printf("%s",p);
        system("PAUSE");
     return 0;
    }
    for compiler everything is allright but its not working.so couldnt get whats wrong please help me
    Last edited by Salem; 02-24-2009 at 01:52 PM. Reason: [CODE][/CODE] go around the code!!!

  2. #2
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14
    You are coding obviously with C. Why are you including one of the C++ header file?
    More information: http://en.wikipedia.org/wiki/Conio.h

    return q;
    free(q);

    You cant free after return.
    Always check return value of realloc to be sure that memory has been occupied for your use....
    Last edited by Skvr; 02-24-2009 at 02:01 PM. Reason: Link

  3. #3
    Registered User carrotcake1029's Avatar
    Join Date
    Apr 2008
    Posts
    404
    You can't realloc without ever having allocated room for that pointer in the first place.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by carrotcake1029 View Post
    You can't realloc without ever having allocated room for that pointer in the first place.
    You can:
    Quote Originally Posted by man realloc
    If ptr is NULL, realloc() behaves like malloc() for the specified size. If size is 0 and ptr is not a null pointer, the space pointed to is freed.
    However, if ptr is just whatever it happens to be on the stack, like in this case, it's undefied.


    For i = 0:
    Code:
    q[i-1]!='1'
    is undefined.

    --
    Mats
    Last edited by matsp; 02-24-2009 at 02:37 PM.
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Feb 2009
    Posts
    10
    guys all right i got u thanks anyway hao can i create a function which cover getch() as like c++ or is there any kind of function in c cover it?

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ibrahim630
    guys all right i got u thanks anyway hao can i create a function which cover getch() as like c++ or is there any kind of function in c cover it?
    Skvr is right to say that <conio.h> is not part of standard C, but wrong to say that it part of standard C++. As far as I know, the library provided by <conio.h>, if it is available, is available as a C library, as Skvr's own link indicates.

    However, as carrotcake1029 and matsp have pointed out, you have more important problems to worry about than the conio library.
    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

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Oh, and if realloc moves the block, this will fail horribly!
    Code:
                                 (char*)realloc(q,(s*sizeof(char)));
    You loose the value returned by realloc.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14
    Yes Laserlight is right, just havent never used <conio.h> myself because i have thought it is Windows platform & C++ thing.I should read the links i post. Im little bit lost anyway what you trying to achieve.
    Is your target to do following:

    Get character one by one as long user enters 1
    when 1 is entered return entered string of entered characters and print them.

    If you want to use getch() include <ctype.h>
    please write your comments in english its easier to understand the code right away, even for the beginner like me.
    Last edited by Skvr; 02-24-2009 at 02:59 PM.

  9. #9
    Registered User
    Join Date
    Feb 2009
    Posts
    10
    '
    ill care next time about french comments anyway thank you for explanation about getch()

  10. #10
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    >If you want to use getch() include <ctype.h>
    Where did the getch() come under ctype.h. The getch is an non-standard function which is defines under conio.h. The alternative for it could be the getchar function.

    >(char*)realloc(q,(s*sizeof(char)));
    Don’t cast the return type realloc. And you get the return address of the realloc to be assigned to something which I don’t anything like. I would suggest creating temp point and assigning the return of realloc to temp pointer and then assign it to the original pointer. Just to be on the safer side. Other you will loss your whole data if the realloc was suppose to fail.

    -ssharish
    Life is like riding a bicycle. To keep your balance you must keep moving - Einstein

  11. #11
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14
    This is not ment to be copy paste code. I put it on this forum so you could see and examine how things are done. And i think anyway that this aint easy for understand without real example. I dont know btw is this rightway to do this but it compiles with no errors and works. A friend showed for me how to play with those pointer indexes they were pretty hard for me.

    Code:
    #include<stdlib.h>
    #include<string.h>
    #include<stdio_ext.h>/*Maybe in Linux only*/
    
    char* user_input(){
      char *ptr;
      char *tmp_ptr;
      int i=0;
      char ch;
      
      printf("Enter letters: (to quit enter 1)\n");
      
      ptr=malloc(1*sizeof(char));
       if(ptr==NULL){
          printf("malloc() failed.\n");
          return 0;
        }
    
       ptr[i]=0;
    
      while(1){
        scanf("%1c",&ch);
        __fpurge(stdin); /*This is not standard, if this dont work find away to get rid of '\n'*/
          if(ch=='1')
    	break;
    
          tmp_ptr=realloc(ptr,i*sizeof(char)+2);
          
          if(tmp_ptr==NULL){ /*Check if space has been allocated succesfully*/
    	printf("realloc() failed.\n");
    	return 0;
          }
          else 
    	ptr=tmp_ptr; /*Enlarge the ptr memory space with allocated space if allocation ok*/
    
         ptr[i]=ch;
         ptr[i+1]='\0';
         i++;
    
         printf("Letters:%s size:%i\n",ptr,i+1);
      }
    
    return ptr;
    }
    
    int main()
    {  
      char *p;
    
      p=user_input();
      printf("String: %s\n",p);
    
      free(p);
    return 0;
    }
    Tell if something is done wrong way or is there a better way to do some parts of the code.
    Last edited by Skvr; 02-26-2009 at 09:12 AM. Reason: English is sometimes hard.

  12. #12
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    there is a better way
    do not realloc on each char - increase buffer in big enough steps at once

    read FAQ how to clear the stdin from the unwanted characters
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  13. #13
    Registered User
    Join Date
    Aug 2008
    Location
    Finland
    Posts
    14
    Is there any other reason why not to realloc every single char than optimization? I can imagine it would be resource consuming if this would be done in some RealWorld application, but because this is an example of using realloc to enlarge previously malloced space i dont see any reason why not to do that in this case.

  14. #14
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by Skvr View Post
    Is there any other reason why not to realloc every single char than optimization? I can imagine it would be resource consuming if this would be done in some RealWorld application, but because this is an example of using realloc to enlarge previously malloced space i dont see any reason why not to do that in this case.
    It is certainly only an optimization, but it is also a good idea to AT LEAST comment that this needs to be done if the difference between initial size and final size is large - a former colleague of mine worked on a problem with a graphics driver, which would allocate another 4KB every time it ran out of buffer. With a 16MB buffer, that was a lot of copying before it was large enough (4096 times if I don't get the math wrong, with an average of 8MB of memory being copies - that's a few gigabytes).

    Of course, for this type of case, the string is likely to be a few hundred bytes, which is not a big issue.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem located but not sure how to fix MouseWheel problem
    By jeppesenbrian in forum C# Programming
    Replies: 2
    Last Post: 07-01-2006, 01:43 PM
  2. small reference problem
    By DavidP in forum C++ Programming
    Replies: 6
    Last Post: 06-21-2004, 07:29 PM
  3. Replies: 5
    Last Post: 12-03-2003, 05:47 PM
  4. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  5. Rename file problem
    By Emporio in forum C Programming
    Replies: 2
    Last Post: 06-05-2002, 09:36 AM