Array for malloc needed

This is a discussion on Array for malloc needed within the C Programming forums, part of the General Programming Boards category; I am trying to allocate the memory of 1KB of size to two variables. I treied with for loop, but ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    39

    Array for malloc needed

    I am trying to allocate the memory of 1KB of size to two variables. I treied with for loop, but i am getting segmentation fault error. I have attached my sample code below. can anyone help to find why that error occurs and whats the solution for my problem

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    main()
    {
     int i,*par[i];
                                                                                                                                 
      for(i=0;i<=2;i++)
      {
       par[i]=(int *)malloc(1024);
       printf("\n%u",par[i]);
      }
                                                                                  
       free(par);
    }
    "Thanks in advance"

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Code:
    int i,*par[i];
    i is not initialized.
    Code:
    for(i=0;i<=2;i++)
    iterates 3 times.
    Code:
    printf("\n&#37;u",par[i]);
    %u is for unsigned ints, not pointers.

    http://faq.cprogramming.com/cgi-bin/...&id=1043284351

    you don't free your mallocs.

    http://faq.cprogramming.com/cgi-bin/...&id=1043284376
    Last edited by robwhit; 03-10-2008 at 02:21 AM.

  3. #3
    CSharpener vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,473
    int *par[i];
    declares array of unknown size

    int* par[2]; - declares array of 2 pointers
    The first 90% of a project takes 90% of the time,
    the last 10% takes the other 90% of the time.

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,211
    Code:
    free(par);
    This is NOT supposed to be free()ed. Each element of the array should be free()ed, however.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Little Array Difficulty
    By G4B3 in forum C Programming
    Replies: 16
    Last Post: 03-19-2008, 12:59 AM
  3. Modify an single passed array element
    By swgh in forum C Programming
    Replies: 3
    Last Post: 08-04-2007, 08:58 AM
  4. Array Program
    By emmx in forum C Programming
    Replies: 3
    Last Post: 08-31-2003, 12:44 AM
  5. two dimensional dynamic array?
    By ichijoji in forum C++ Programming
    Replies: 6
    Last Post: 04-14-2003, 04:27 PM

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