Thread: anything wrong with this code?

  1. #16
    Registered User
    Join Date
    Dec 2004
    Posts
    20
    sizeof(char) is always 1. Code is simpler by removing the multiplication.
    Code:
    char *p = malloc(10);
    if (p == NULL) {
        perror("malloc");
        return 1;
    }

  2. #17
    Hello,

    Whenever you allocate memory, you must free it. To keep this simple the ANSI-C function free() deallocates dynamically allocated memory. A compatible way to free memory allocated by malloc() is free().


    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  3. #18
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    Quote Originally Posted by [Ren]
    sizeof(char) is always 1. Code is simpler by removing the multiplication.
    Code:
    char *p = malloc(10);
    if (p == NULL) {
        perror("malloc");
        return 1;
    }
    and leaves the OP to perhaps think all he needs to give malloc as an argument is a number? no thanks,
    a little implicit, but i'm sure you understand.
    if nothing else my code gets you into the habit of specify the sizeof of each storage area you need. Its assumed the OP didn't know this, based on his origianl entry.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  4. #19
    Registered User
    Join Date
    Dec 2004
    Posts
    20
    Quote Originally Posted by caroundw5h
    and leaves the OP to perhaps think all he needs to give malloc as an argument is a number? no thanks,
    if nothing else my code gets you into the habit of specify the sizeof of each storage area you need. Its assumed the OP didn't know this, based on his origianl entry.
    a, so. When using sizeof, is it not better to avoid using the type directly?
    Code:
    char *p = malloc(10 * sizeof *p);

  5. #20
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    It's best written as
    Code:
    char *p = malloc( 10 * sizeof *p );
    On the principle that if there is a way to do things which is always correct, then that is the preferred way to do it. Then you don't have to think about it since that will be the way it is done out of habit, and that bit of code will be correct out of habit.

    Imagine you started with
    Code:
    char *p = malloc ( 10 * sizeof(char) );
    or
    char *p = malloc ( 10 );
    Now suppose you come along later and decide you want a wchar_t instead.

    In some hasty moment, you only change one thing instead of two.
    Code:
    wchar_t *p = malloc ( 10 * sizeof(char) );  // oops, forgot to change the sizeof
    or
    wchar_t *p = malloc ( 10 );  // oops, forgot to add a sizeof
    Neither will draw a compiler error message, but pain and suffering can't be far away.

    I bet now you think this is a reason to use a cast, so you get an error message when you change the type of the pointer. Whilst this is true (you will get an error message), it is not a reasonable tradeoff.
    Code:
    char *p = (char*)malloc( 10 * sizeof(char) );
    Sure you get a "initialization from incompatible pointer type" message if you change the type of p, but only at the expense of suppressing a rather more serious "initialization makes pointer from integer without a cast" which you would otherwise get if you failed to include stdlib.h in the first place.

    The other downside is that you've now got 3 things to change, and still no guarantee that you won't end up with equally broken code as before.
    Code:
    wchar_t *p = (wchar_t*)malloc( 10 * sizeof(char) );  // oops, you still lose!
    Except now having compiled it once, got a "initialization from incompatible pointer type" message and fixed it, you might be more tempted to believe that the code is correct because you've made the change. Several crashes later, you have a "DOH!!" moment and you're back on track.

  6. #21
    Quote Originally Posted by caroundw5h
    I'm sure polyglots are interesting in themselves and still another avenue for programmers to mix c and C++ code. Please dont' pretend like it doesn't happen salem.
    May it happens doesn't make it good practice. People do mistakes. I won't encourage them...
    its actully so common there is a language called C/C++
    There is no such a monster. C an C++ are separated and different languages.
    Emmanuel Delahaye

    "C is a sharp tool"

  7. #22
    Quote Originally Posted by thinhare
    Yes, when I replace *s with s[], it work properly.

    I'm wondering why there's no boundary indeed for an array, to which we have even designate a number of size limit.

    e.g.,

    char s[100] = "Hello ";
    This string is expandable (e.g. with strcat())
    it still works even if 100 is omitted. and seems the string could be appended to any desired longer. like this:

    char s[] = "Hello ";
    This one is not expandable (it occupies the whole room already). It can be shrinked.

    Note that the size of the array (sizeof operator) will remain unchanged, only the length of the string (strlen()) will change.
    Emmanuel Delahaye

    "C is a sharp tool"

  8. #23
    Quote Originally Posted by thinhare
    But it's interesting that even C built-in "strcpy" doesn't do anything to check the bound of the array.
    strcpy() and strcat() have no size info. strncpy() and strncat() have it, but their correct use is not trivial...
    that might just be that so-called flexibility.
    No It's called simplicity. The C language is a sharp tool. Can be dangerous in beginner's hands...
    Emmanuel Delahaye

    "C is a sharp tool"

  9. #24
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    There is no such a monster. C an C++ are separated and different languages.
    That was actually a joke.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  10. #25
    Registered User
    Join Date
    Apr 2004
    Posts
    210
    Quote Originally Posted by caroundw5h
    unless you're attempting to make your C program C++ compatible. the casting is redundant in C, a necessity in C++.
    That may well hold truth, but I somehow doubt the original poster tries to learn C and C++ at the same time.
    Rather I'd say, malloc was casted because stdlib.h was not included - thereby causing the compiler to default to return-type int and complain about the type mismatch. At least I know I once did that :-)
    main() { int O[!0<<~-!0]; (!0<<!0)[O]+= ~0 +~(!0|!0<<!0); printf("a function calling "); }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 07:10 AM
  2. what is wrong with this code please
    By korbitz in forum Windows Programming
    Replies: 3
    Last Post: 03-05-2004, 10:11 AM
  3. I cant find what is wrong with this code
    By senegene in forum C Programming
    Replies: 1
    Last Post: 11-12-2002, 06:32 PM
  4. Anyone see what is wrong with this code?
    By Wise1 in forum C Programming
    Replies: 2
    Last Post: 02-13-2002, 02:01 PM
  5. very simple code, please check to see whats wrong
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-10-2001, 12:51 AM