Hi All ,
This is my code snippet

typedef struct {
char *name;
} CELL;


typedef struct {
CELL *cell;
char *name;
} INST ; 

int main () {
INST **top_inst_list ;
int i,j;
char string_name[100];

printf("Enter number of insts in design\n") ;
scanf("%d",&i);

top_inst_list = (INST **)malloc(sizeof(INST*)*i) ;

for ( j = 0; j < i; j++ ) {
top_inst_list[j] = (INST *)malloc(sizeof(INST));
top_inst_list[j]->name = (char *)malloc (sizeof(char) * 10);
top_inst_list[j]->cell->name = (char *)malloc (sizeof(char) * 5);
}

The last two lines are giving segmentation fault , i have followed this thread (http://www.daniweb.com/software-development/c/threads/147119/page2)
and started this program

Any help regarding this would be helping

Thanks
Nataraja G

Edited 4 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

You didn't allocate memory for the cell inside the INST.

for ( j = 0; j < i; j++ ) {
      top_inst_list[j] = (INST *)malloc(sizeof(INST));
      top_inst_list[j]->name = (char *)malloc (sizeof(char) * 10);
      // You need to allocate memory for the CELL before you start to access 
      // top_inst_list[j]->cell->name
      top_inst_list[j]->cell = (CELL *)malloc (sizeof(CELL));   // <--- ADDED
      top_inst_list[j]->cell->name = (char *)malloc (sizeof(char) * 5);
   }

Edited 4 Years Ago by histrungalot: n/a

Thanks man the code is working
still there is lot of ground to cover , will be posting queries if i have any prob's

Cheers

Hi guys ,
Need an optimized way of doing this

By default if i allocated 10bytes for a string and
after reading the string from input and now i found out 7bytes are enough to store the string ,
i want to release the unused memory

char *str ;
int len ;
// allocated some amount of space
str=(char *)malloc(10* sizeof(chat));      

// read some data
scanf("%s",str) ;

len = strlen(str);
// for null char , i guess strlen doen't count that
len = len + 1; 
if ( len < 10) {
    tmp=(char *)malloc(len * sizeof(char));  
    if(tmp!=NULL) {
        strcpy(tmp,str);
        free(str);
        str = tmp ;
    } else {
       exit 0;
    }
}

IS THERE ANY BETTER AND QUICK way of doing this ?

This is similar to a question I answered a couple days ago. You can use realloc.
I think the bigger issue is how do you know that the user is not going to type in more than 9 characters?
You need to make sure that you don't over-run the memory you created.
Here is come code. I tested it a bit, so if you use it test it some more.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
   char *str,*tmp;
   int len,indx=0,
       bufsize = 10*sizeof(char);
   // allocated some amount of space
   str=(char *)malloc(bufsize);      

   // --------> Protect Over-Run <-------
   // read some data
   while ((fgets(&str[indx],bufsize-indx,stdin)) != 0) {
       if (!(tmp = strchr(str,'\n'))) {
           indx = strlen(str);
           bufsize *= 2;
           printf("Increasing to %d\n",bufsize);
           tmp = (char *)realloc(str,bufsize);
           str = tmp;
           continue;
       }
       else {
          // Just getting rid of the '\n'
          *tmp = '\0';
          printf("Read in: %s\n",str);
          break;
       }
   }
   // --------> Protect Over-Run <-------

  // ---------> Your question <----------
  // Here is where extra memory get released
  len = strlen(str);
  // for null char , i guess strlen doen't count that
  len = len + 1; 
  if ( len <  bufsize) {
      printf("Realloc from %d to %d\n",bufsize, len);
      tmp=(char *)realloc(str,len * sizeof(char));  
      if(tmp!=NULL) {
          str = tmp;
      } else {
         exit(0);
      }
  }
  // ---------> Your question <----------
  free(str);
  return 0;
}

Output:

$ ./a.out
Test
Read in: Test
Realloc from 10 to 5
$ ./a.out
This is a test to see if what I coded is working correctly!
Increasing to 20
Increasing to 40
Increasing to 80
Read in: This is a test to see if what I coded is working correctly!
Realloc from 80 to 60
$

Thankz histrungalot , i shall be using your snippet :)
and i have one doubt , how to query the array size ? which we have allocated using malloc
I think you are just doubling the array size

Here is my problem :
i have pointer(A) which point's to a list of pointer's (B C D E)
i need to update this pointer list , by reallocating memory for A but to do this i need to know the current size of list pointed by A (in this case 4) and i cant maintain a counter for A


Can someone tell me a work-around for this

come on guys :(
i am stuck at this point !
how should i be doing this without using a counter ?

I was waiting to see if anyone else was going to answer because you are not going to like my answer.
In C there is no way to know the size of a dynamically allocated array. You are going to have to store the size somewhere. When you allocate memory, the OS knows the amount but you don't have access to that.
I also didn't understand why you needed it. If you are trying to reallocate the amount of memory for the pointer array, you should know the size because in order to use those points at so point you may have had a for loop that went from the first to the last element. Therefore you know how many pointer are in the array and can allocate memory using that value.

Hi ,
My requirement is like that , need to update the database/pointers ( 1000000+ ) depending on the category and i didn't want to maintain a counter for database length because each counter may vary from 1-1000+ and its just waste of memory
the problem is i dont know the exact length while allocating memory at the first short as and then data arrives depending on categories i need to add data to that existing pointer

Can this be done in C++ ?

Yes. If you use a STL vector.
http://www.cplusplus.com/reference/stl/vector/
"Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements."

But instead of storing a variable to hold the size of the array, vector uses this structure below.

struct _Vector_impl
      : public _Tp_alloc_type
      {
        _Tp*           _M_start;
        _Tp*           _M_finish;
        _Tp*           _M_end_of_storage;
        _Vector_impl(_Tp_alloc_type const& __a)
        : _Tp_alloc_type(__a), _M_start(0), _M_finish(0), _M_end_of_storage(0)
        { }
      };

And when the vector runs out of memory it allocates 2 time the size that it used to be which is exactly what we did earlier.

// Code from vector.tcc
 template<typename _Tp, typename _Alloc>
    void vector<_Tp, _Alloc>::_M_insert_aux(iterator __position, const _Tp& __x)
    {
        ... 
        ...
        size_type __len = __old_size != 0 ? 2 * __old_size : 1;

Allocating memory and then moving data is expensive and you don't want to do it often. That is why the rule of thumb is, when you need more memory allocate 2 time what you had before. That way you shouldn't have to get more for sometime later.

Hi ,
After storing all the data , can we free the unused memory ?
If we have allocated 100bytes and I'm using 51 bytes , can I free those 49bytes ? realloc can do that but STL vector does it support ?

realloc can do that but STL vector does it support ?

std::vector has historically not shrunk memory when the size is reduced to improve the performance of furtuer insertions. The idiom from before C++11 was using the swap() member function:

vector<T>(a).swap(a);

But with the coming of C++11, std::vector now has a (albeit non-binding, so the request may be ignored) shrink_to_fit() member function.

This article has been dead for over six months. Start a new discussion instead.