Thread: Dynamic memory allocation. Very simple question.

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by WoodSTokk
    Code:
    fflush(stdout); // no newline at the end of last output - flush it!
    You don't actually need this because on the next line there is a scanf or getc call which will force the flushing of the output buffer.
    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

  2. #17
    Registered User
    Join Date
    May 2017
    Posts
    101
    Thank you for your code Laser. I want to study it, however, I wonder I have not enough knowledge to understand some parts. I didn't study stderr so I have no idea what this function does.

  3. #18
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Well, stderr is basically a separate output stream. The principle behind stderr is that you may want to redirect the program's output into a file (or pipe it into another program), but still have warnings and errors appear on the terminal. You can of course redirect stderr too. It's not that complicated, take a look at this page.
    Devoted my life to programming...

  4. #19
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by laserlight View Post
    You don't actually need this because on the next line there is a scanf or getc call which will force the flushing of the output buffer.
    Oh, thanks for the information, Laserlight. I havn't know that.
    Other have classes, we are class

  5. #20
    Registered User
    Join Date
    May 2017
    Posts
    101
    Thank you for your information. In the meantime I study laser code, what if I want to get the string reverted? For example: Hi my name is Jorge -> egroJ si eman ym iH

    Using the same code, I tried it but messed up everything and fails, doesnt print anything or weird characters:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
        char c;
        char *ptr;
        char *ptrb;
        int num, i=1;
    
        printf("Insert the number of characters: ");
        scanf("%d", &num);
    
        ptr=(char *) malloc((num+1)*sizeof(char));//Allocate the text
        if (ptr==NULL) {
            printf("There is not enough memory to allocate");
        } else {
            printf("Insert the text to revert: ");
            scanf(" %c", ptr);
            while (c!='\n' && i<=num-1) {
                c=getc(stdin);
                ptr[i]=c;
                i++;
            }
        }
        ptr[i]='\0';
        free(ptr);
    
        ptrb=(char *) malloc((num+1)*sizeof(char));//Allocate the reverted text
        if (ptrb==NULL) {
            printf("There is not enough memory to allocate");
        } else {
            while (c!='\n' && i<=num-1) {
                *(ptrb+i)=*(ptr-i-1);//Tail of string will be copied to beginning
                i++;
            }
        }
        ptrb[i]='\0';
    
        printf("\nText reverted: %s\n", ptrb);
        free(ptrb);
    
        return 0;
    }
    The exercise may be easier than I am thinking, but the fact is I never reverted a string. I accept any idea. Of course I know my code is a mess.
    Last edited by JorgeChemE; 06-12-2017 at 05:15 AM.

  6. #21
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    > *(ptrb+i)=*(ptr-i-1);//Tail of string will be copied to beginning
    You're too late, you already called free(ptr);
    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. #22
    Registered User
    Join Date
    May 2017
    Posts
    101
    Quote Originally Posted by Salem View Post
    > *(ptrb+i)=*(ptr-i-1);//Tail of string will be copied to beginning
    You're too late, you already called free(ptr);
    I am trying another cleaner code. What do you think?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char c;
        char *ptr;
        int num, i=1;
    
        printf("Insert the number of characters: ");
        scanf("%d", &num);
    
        ptr=(char *) malloc((num+1)*sizeof(char));
        if (ptr==NULL) {
            printf("There is not enough memory to allocate");
        } else {
            printf("Insert the text: ");
            scanf(" %c", ptr);
            while (c!='\n' && i<=num-1) {
                c=getc(stdin);
                ptr[i]=c;
                i++;
            }
        }
        ptr[i]='\0';
        for(num=i-1; num>=0; num--) {
            putchar(ptr[num]);
        }
        printf("\n");
        free(ptr);
    
        return 0;
    }
    I don't know what I was thinking before, please forgive the previous code.

    This code do the job if the word has equal or less characters than declared:

    Hello: olleH

    What if I declare 10 characters and the word is longer?

    Insert the number or characters: 10
    Insert the text: Unimaginatively
    tanigaminU

    Process returned 0 (0x0) execution time : 10.478 s
    Press any key to continue.
    Last edited by JorgeChemE; 06-12-2017 at 05:40 AM.

  8. #23
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,665
    > What if I declare 10 characters and the word is longer?
    What do you want to happen?

    Complain to the user that the word is too long?
    Ignore their poor guess at 'num', and just allocate enough space for whatever they type in?
    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. #24
    Registered User
    Join Date
    May 2017
    Posts
    101
    Quote Originally Posted by Salem View Post
    > What if I declare 10 characters and the word is longer?
    What do you want to happen?

    Complain to the user that the word is too long?
    Ignore their poor guess at 'num', and just allocate enough space for whatever they type in?
    Insert the number or characters: 10
    Insert the text: Unimaginatively
    tanigaminU

    The thing is to allocate the memory that the user insert through keyboard (my instructor seems to be a fanatic of keyboard use) and revert the characters that the user insert through keyboard. In this example, with the last code I posted I would expect:

    Insert the number or characters: 10
    Insert the text: Unimaginatively
    ylevitanig

    The program now reverts the first 10 characters, instead of counting characters from the end.

  10. #25
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    (my instructor seems to be a fanatic of keyboard use)
    I thought you said:
    Now I am learning by myself,
    So if you're learning by yourself then why worry about how your instructor wanted things? IMO, you instructor was teaching from the past so why not come into the present and learn modern C (or C++) instead.

    By the way even if you're making a program that gets inputs from the console it is possible to redirect the input to get the information from a file.

    In this example, with the last code I posted I would expect:
    Why would you expect "ylevitanig"? If the user entered 10 for the size of the string I would expect the input to stop taking characters at 10 characters, no matter how many characters the user entered, to prevent buffer overflow errors.

    Jim

  11. #26
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    Quote Originally Posted by JorgeChemE View Post
    I am trying another cleaner code. What do you think?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        char c;
        char *ptr;
        int num, i=1;
    
        printf("Insert the number of characters: ");
        scanf("%d", &num);
    
        ptr=(char *) malloc((num+1)*sizeof(char));
        if (ptr==NULL) {
            printf("There is not enough memory to allocate");
        } else {
            printf("Insert the text: ");
            scanf(" %c", ptr);
            while (c!='\n' && i<=num-1) {
                c=getc(stdin);
                ptr[i]=c;
                i++;
            }
        }
        ptr[i]='\0';
        for(num=i-1; num>=0; num--) {
            putchar(ptr[num]);
        }
        printf("\n");
        free(ptr);
    
        return 0;
    }
    Why do you cast the returned value of 'malloc()'? Complains your compiler without the cast?
    What happens if your program doesn't receive memory at 'malloc()'?
    Code:
    …
        ptr=(char *) malloc((num+1)*sizeof(char));
        if (ptr==NULL) {
            printf("There is not enough memory to allocate");
        } else {
            …
        }
        ptr[i]='\0'; // BOOOMM (ptr points to NULL)
    …

    Laserlight and I have show you, how you handle the problems on a better way, but you ignore our recommendations.
    Other have classes, we are class

  12. #27
    Registered User
    Join Date
    May 2017
    Posts
    101
    I'm still solving the remaining exercises, 6, but once finished, I will need good books to learn by myself. In fact, I would want to ask about resources to learn about: pointers, string management, POO, dynamic memory allocation.

    No, I don't ignore, I am now trying to understand the code posted by laserlight. I will need some help to understand some lines:

    Code:
    while ((c = fgetc(stdin)) != '\n' && c != EOF);
    In theory, we studied fgetc but the course was too fast for me that I still don't understand some concepts. I admit, at the moment I forgot what fgetc does. Another question in this line is EOF. I remember that EOF is end of the line in a file, is the equivalent of '\n'? We did some exercises with that but using files, opening and closing (fopen, fclose).

    Code:
    fprintf(stderr, "There is not enough memory.\n");
    We never used fprintf but is in a ppt I should study now. At the moment, I don't have any idea about fprintf but I will study it today.

    Code:
    if (!fgets(ptr, num, stdin))
    You explained me this and a quick commentay was made at class, but still I need to study fgets.

    Code:
    ptr[strcspn(ptr, "\n")] = '\0';
    I think you are complaining because I'm not using this. The thing is I don't understand strcspn, we didn't touch it at class. Maybe is a good time to learn this concept.

    There are more questions I have. You are using functions that concerns files but you don't open and close files. I don't know why we were always using fopen, fclose. As I stated before, this course required some previous knowledge but I think 90% of the students were in the same situation like me, we were lost at many points.

    Replying to Jim, I don't feel able to start learning "modern" C++ at this moment because I don't have the basic knowledge yet but of course, I want to learn it by myself in the future.

    I wanted to start another exercise, but don't mind, I have more than enough time now. I think I will be better studying the laserlight code. I copied and pasted the code and for the first time compiled in C instead of C++. I tried it, the code works perfectly and I wnt to understand it.

  13. #28
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    To learn C++ you don't need basic knowledge. The less you know about c the better since you would need to forget most of it.
    Stroustrup: FAQ
    Learning C makes only sense if you want to write code for Linux kernel or the next version of the stl.
    The exercise in C++:
    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
      std::cout << "Enter the number of characters: ";
      size_t num_chars = 0;
      std::cin >> num_chars;
    
      std::cout << "Enter the characters to revert: ";
      std::string buffer;
      std::cin.ignore(255, '\n'); // removes dangling '\n'
      std::getline(std::cin, buffer);
    
      if (buffer.size() > num_chars) // if more characters were entered
        buffer.resize(num_chars); // remove surplus charcters
    
      std::string reversed(buffer.rbegin(), buffer.rend()); 
    
      std::cout << "Your reversed string: " << reversed;
      return 0;
    }

  14. #29
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    In theory, we studied fgetc but the course was too fast for me that I still don't understand some concepts. I admit, at the moment I forgot what fgetc does.
    I hope you remember that the internet has these wonderful tools called search engines that allow you to type in things like "fgetc()" to allow you to search for that item. All standard C or C++ functions have documentation available on the net, the problem will be that there will be so many results of the search that you'll need to figure out what links are useful.

    Another question in this line is EOF. I remember that EOF is end of the line in a file, is the equivalent of '\n'?
    No, EOF has nothing to do with the end of line, it is a macro that is used to detect the End Of File.

    We never used fprintf but is in a ppt I should study now. At the moment, I don't have any idea about fprintf but I will study it today.
    Considering how you were being taught, I would recommend you go the "search engine" route, you'll probably get much more current information that is probably easier to read and understand. The only difference between fprintf() and printf() is that fprintf() will print to any output file, printf() will print only to the console. You also should know that the run time system automatically opens three standard "files" when your program starts, stdin, stdout, and stderr. These "files" are usually directed to the console for input (stdin), output (stdout), and error output (stderr).

    Replying to Jim, I don't feel able to start learning "modern" C++ at this moment because I don't have the basic knowledge yet but of course, I want to learn it by myself in the future.
    Even if you never want to learn C++ you really need to start learning Modern C instead of the outdated version of C that your instructor was teaching. And since you're learning C I recommend you always use a current C compiler that is compiling for one of the current C standards (C11 or C99). And by the way I don't consider the Microsoft C compiler a "modern C compiler", since it doesn't fully support either of the current standards.

    I wanted to start another exercise, but don't mind, I have more than enough time now. I think I will be better studying the laserlight code.
    Don't forget those search engines when "studying" code you find on the internet, if there are parts you don't understand your first stop should be your search engine of choice to find and read some documentation. And don't forget that you can experiment with the code supplied by others, such as the code supplied by laserlight, by modifying the code to try to figure out what is happening for yourself. Searching and finding documentation that you understand and then "playing" with the functions in question will probably help you understand the code faster than always asking questions of others. And by the way this "playing" will help you develop problem solving skills that are important. So go ahead and study the code supplied, by reading the documentation for the standard functions and try to adapt the code to other problems. But remember you will probably learn to program faster by programming many small programs that solve many small problems. And when trying to understand some new concept many times it is easier to write a program with the absolute minimum code to "exercise" the "unknown concept".




    Jim
    Last edited by jimblumberg; 06-13-2017 at 08:36 AM.

  15. #30
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    The explanation of 'fprintf()' is very simple.
    Normaly, you output information with 'printf()'.
    In Unix, Linux, BSD, MasOS X (and AFAIK also in Windows), every program has 3 streams:
    stdin = the standard input stream where the program reads in informations
    stdout = the standard output stream where the informations goes to
    stderr = also a output stream, but should be used for errors
    If you work on the console, you will not see a difference, because 'stdout' and 'stderr' goes both to the console.

    If you write a script, many times a command read the output of a previously command.
    But if the first command have a problem, the second command read not the expected information, it reads a error message.
    Therefor, only the stdout of the first command is piped to the second command.
    The stderr goes to console so you can see there is a problem.
    Under Linux you can check it with the following line:
    Code:
    $ ls xxx > out.txt 2> err.txt
    The command 'ls' (stand for 'list') show you the content of the directory named 'xxx'.
    The output of 'ls' will be written to ('>' = redirection of stdout) the file 'out.txt'.
    But if this directory doesn't exist, 'ls' bring up a error message and this goes to ('2>' = redirection of stderr) the file 'err.txt'.
    The number 2 in the redirection means 'stream 2' and this is 'stderr'. 'stdout' is 'stream 1', so you can also write '1>', but if you leave the number away, the console take 'stream 1' automaticly.
    The stdin is 'stream 0', but you can't redirect a input stream to a file. You can only redirect a file to a input stream.

    Okay, now we can output to 'stdout' and 'stderr'?
    You have used 'printf()' previously to output information from your program.
    'printf()' send the output allways to 'stdout' (stream 1).
    'fprintf()' is the same as 'printf()', but have a additional parameter, the stream to write to.
    Code:
    printf("Hello World!\n");
    is the same as:
    Code:
    fprintf(stdout, "Hello World!\n");
    Now, if you write:
    Code:
    fprintf(stderr, "Hello World!\n");
    the output goes to 'stderr' (stream 2).
    If you use your program in a script, you can now see if there are expected information (stream 1) or if there are a problem (stream 2).
    This is also the matter of the returned value of 'main()'.
    If the program runs without problems, it should return a value that reflect that (mostly 0).
    And if there are a problem, return a differend value.
    Code:
    int main (void) {
        …
        if (err_check) return 1; // PROBLEM! quit the program and return non 0!
        …
        return 0; // no problems, return 0
    }
    Also 'ls' do that. Check it:
    Code:
    $ ls xxx > out.txt 2> err.txt
    $ echo $?
    2
    I hope my explanation is okay with my bad english.
    The standard functions in 'stdio.h' are very good descriped on <cstdio> (stdio.h) - C++ Reference.
    On that side, you find also the other standard headers. Realy cool, i use also that side every time I hack on a program.
    Oh, and on Linux, you have the manual pages (like 'man fprintf') if you have the documentation installed.
    Last edited by WoodSTokk; 06-13-2017 at 11:18 AM.
    Other have classes, we are class

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dynamic Memory Allocation - A Simple DOS Text Game
    By pavil in forum C++ Programming
    Replies: 15
    Last Post: 05-12-2014, 06:32 AM
  2. Dynamic memory allocation question.
    By peripatein in forum C Programming
    Replies: 14
    Last Post: 05-24-2013, 02:03 PM
  3. Question about dynamic memory allocation
    By dayanike in forum C Programming
    Replies: 2
    Last Post: 12-11-2012, 08:35 AM
  4. Dynamic Memory Allocation Question
    By somniferium in forum C Programming
    Replies: 6
    Last Post: 10-12-2012, 07:51 PM
  5. Dynamic Memory Allocation Question
    By Piknosh in forum C++ Programming
    Replies: 1
    Last Post: 04-14-2004, 01:55 PM

Tags for this Thread