Realloc problem

This is a discussion on Realloc problem within the C Programming forums, part of the General Programming Boards category; Code: int *a=NULL; realloc(a, sizeof(int *)); a[0] = 1; I got segmentation fault at a[0]=1. May I know why is ...

  1. #1
    Registered User
    Join Date
    Dec 2004
    Posts
    163

    Realloc problem

    Code:
    int *a=NULL;
    
    realloc(a, sizeof(int *));
    a[0] = 1;
    I got segmentation fault at a[0]=1. May I know why is this so? I'm planning to use realloc instead of malloc because *a is a buffer which will be placed in a FOR loop and its size will constantly change.

    Any help will be much appreciated!

    Lastly, is there any good performance analysis tools in Linux that can measure cache misses, disk read, etc occuring in the program that I created?

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You should be allocating the size of an integer, not the size of a pointer. You already have a pointer.
    Code:
    int *ptr = realloc( ptr, sizeof( int ) * numberofintsyouwant );
    ptr[0] = 1;
    Although I really don't see the point of using realloc here instead of just using malloc.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    ---
    Join Date
    May 2004
    Posts
    1,379
    if its going to be in a loop then use malloc once before the loop then use reallac in the loop.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    Check out my reply here
    why isn't doing what I want it to do?

    1. Shows you that realloc returns a result
    2. Avoids ptr=realloc(ptr,n), which is a really bad way of leaking memory if realloc fails
    3. Shows one way of extending the amount allocated in blocks, rather than one at a time
    4. Shows that an initial malloc isn't necessary, because ptr=realloc(NULL,n) is identical to malloc anyway.

    > Lastly, is there any good performance analysis tools in Linux
    Well first of all, you make sure your program is finished and working (it's a waste of time trying to do this before the program is finished). A complete program then acts as a baseline for optimisation.
    Then you get some real-world data to play with (test data is both smaller, and selective, so it tells you nothing).
    Then you use "gcc -pg prog.c" to compile your program, then the "gprof" program to analyse your program to see where all the time is spent.
    Since you have a baseline, you can tell how effective any "improvements" were.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User
    Join Date
    Dec 2004
    Posts
    163
    Thanks guys for the help! Especially to Salem, I use your code format and it can work! And GPROF is very useful. Thanks again man!


    quzah, I use realloc(a, sizeof(int *)) and it worked for me. I don't know the difference between them, it shouldn't pose a problem for me right?

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,434
    > it shouldn't pose a problem for me right?
    It's the difference between being lucky and being right.
    Using sizeof(int*) instead of sizeof(int) is down to being lucky, and that you probably get the same answer (say 4) on your machine.

    If you had sizeof(big_struct*) where you actually meant sizeof(big_struct), you would rather rapidly become unlucky.

    The best (and easiest) approach is to not refer to the type at all, but refer to what the variable points to. These do the same thing, use the variable to determine the size.
    Code:
    int *p = malloc ( 10 * sizeof(p[0]) );
    double *q = malloc ( 20 * sizeof *q );
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    fraziss, try this exercise, compile/analyze until you KNOW *int is bad , even though it works (but won't work for other datatypes like doubles and such).
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    struct Hello {
        int t;                      // 4 bytes
        double d;                   // 8 bytes
        float f;                    // 4 bytes
    };
    
    int main(void)
    {
        struct Hello *Shello = malloc(1 * sizeof(*Shello));
        /* Samething:
           struct Hello *Shello = malloc(1 * sizeof(struct Hello));
           struct Hello *Shello = malloc(sizeof(struct Hello)); */
    
        printf("Sizeof *Shello:       %d\n", sizeof(*Shello));  //16
        printf("Sizeof struct Hello:  %d\n", sizeof(struct Hello));   //16
        printf("Sizeof Shello:        %d\n", sizeof(Shello));   //4
        printf("Sizeof *struct Hello: %d\n", sizeof(struct Hello *)); //4
        printf("Sizeof double:        %d\n", sizeof(double));   //8
        printf("Sizeof *double:       %d\n", sizeof(double *)); //4
    
        /*
           A pointer is always going to be 4 bytes because it is an integer.
         */
        return 0;
    }

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well you could at least free what you allocate. Didn't we have this discussion before?

    Code:
    printf("Sizeof Shello:        %d\n", sizeof(Shello));   //4
    Try compiling as C instead of C++. This is not valid.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Software Developer jverkoey's Avatar
    Join Date
    Feb 2003
    Location
    University of Waterloo
    Posts
    1,903
    /*
    A pointer is always going to be 4 bytes because it is an integer.
    */
    I believe in 64 bit OSs, this is not true, correct me if I'm wrong, but I believe in 64 bit OSs, pointers are 8 byte values.

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by jverkoey
    I believe in 64 bit OSs, this is not true, correct me if I'm wrong, but I believe in 64 bit OSs, pointers are 8 byte values.
    Correct. There is nothing in the standard to my knowledge that states "a pointer must be 4 bytes". Furthermore, all of the blue comments proclaiming size are also not guarinteed values. It's just what happens to be the value for their compiler.

    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Quote Originally Posted by quzah
    Well you could at least free what you allocate. Didn't we have this discussion before?
    I want my customers to have memory leaks! lol, no no I just keep forgetting, you've reminded me like 2-3 times . I'll write that on my board...now that it's in front of my face, I should remember next time! lol.....

    Quote Originally Posted by quzah
    Try compiling as C instead of C++. This is not valid.
    I'm compiling as C, using gcc. I know I'm not compiling as C++ because I get errors when I try to import iostream, I think I'm using C99 or something relatively close.

    Quote Originally Posted by jverkoey
    I believe in 64 bit OSs, this is not true, correct me if I'm wrong, but I believe in 64 bit OSs, pointers are 8 byte values.
    I knew I was telling lies, but for most computers running today, it's 4 bytes.

    Quote Originally Posted by quzah
    It's just what happens to be the value for their compiler.
    I didn't know it was a compiler issue, I thought it was a language/system issue.
    Last edited by Kleid-0; 01-24-2005 at 07:53 AM.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Kleid-0
    I'm compiling as C, using gcc. I know I'm not compiling as C++ because I get errors when I try to import iostream, I think I'm using C99 or something relatively close.
    No.

    Code:
    #include<stdio.h>
    int main( void )
    {       
            struct foo { int x; } x;
            printf("The size of foo is %d.\n", sizeof( foo ) ); /* won't compile */
            return 0;
    }
    
    /*
    ~/gcc -v
    gcc version 3.3.4 (Debian 1:3.3.4-13)
    
    ~/gcc -o incorrect incorrect.c -Wall -std=c99
    incorrect.c: In function `main':
    incorrect.c:5: error: `foo' undeclared (first use in this function)
    incorrect.c:5: error: (Each undeclared identifier is reported only once
    incorrect.c:5: error: for each function it appears in.)
    incorrect.c:4: warning: unused variable `x'
    */
    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    Code:
    #include<stdio.h>
    int main( void ) {       
       struct foo { int x; } x;
       printf("The size of foo is %d.\n", sizeof( struct foo ) ); /* shall compile */
       return 0;
    }
    
    /*
    Shiva:/home/kleid/Programming/Laboratory#gcc -v
    gcc version 3.3.5 (Debian 1:3.3.5-6)
    
    Shiva:/home/kleid/Programming/Laboratory#gcc correctCompile.c -std=c99 -Wall 
    correctCompile.c: In function `main':
    correctCompile.c:3: warning: unused variable `x'
    */
    Last edited by Kleid-0; 01-24-2005 at 05:13 PM.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Of course that compiles. I see the problem. I misread the origional name of your structure. Like so:
    Code:
        printf("Sizeof Shello:        %d\n", sizeof(Shello));   //4
    I though the name of your structure was "Shello", not the pointer name. In C++, this is legal:
    Code:
    struct Shello { int x; } instance;
    
    cout << "Shello is " << sizeof Shello << "\n";
    I was thinking you'd used the name of the structure itself, rather than the instance. You can in C++, but not in C. My mistake.

    That's why my sample code was the way it is.

    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    UT2004 Addict Kleid-0's Avatar
    Join Date
    Dec 2004
    Posts
    656
    I see what you mean, I'm glad everything is ok now, I love these deep arguements, and sometimes I'm really way off. So I keep arguing until happiness is received! Amen!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. writing a pack-style function, any advices?
    By isaac_s in forum C Programming
    Replies: 10
    Last Post: 07-08-2006, 08:09 PM
  2. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 05:24 PM
  3. using realloc
    By bobthebullet990 in forum C Programming
    Replies: 14
    Last Post: 12-06-2005, 04:00 PM
  4. Replies: 5
    Last Post: 11-07-2005, 10:34 PM
  5. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM

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