1

I'm attempting to create a dynamic array in C but I am a little confused on how to go about it. Firstly calloc() seems to be giving me strange results. I have some code as follows:

struct utmp userRec;
printf("%d\n", sizeof(userRec)); //should print size of object
structutmp * roster = calloc(1, sizeof(userRec));
printf("%d\n", sizeof(roster)); //should print total size of all objects in array
printf("%d\n", sizeof(roster)/sizeof(roster[0])); //should print number of elements in array

Now the results of the prints are:

384
8
0

This output seems odd to me, since the first print seems okay. If that is the size of that particular object then fine, but then I thought the size of the array roster would be equal to that, since calloc was told to make room for one object with the same size as userRec. Finally the result of this one is also confusing. Shouldn't the result of this calculation be one? Since again I allocated space for one struct utmp, then the result should be that I have room for one struct utmp. Not zero. Any insight into why I'm getting these results would be appreciated!

Also one more question for if/when I finally get calloc() to work for me. I would like this array to be able to grow! I read that the realloc() function could be useful for this, but I am unsure. Does realloc() maintain the state of the array while adding more space? Also does free() return a pointer to the same memory block so I could call realloc() on it again?

Thanks for any answers!

  • what does `struct` utmp look like? – machine_1 Feb 26 '19 at 22:10
  • `roster` is a pointer, not an array. You can't know the size of the underlying data with `sizeof` on a pointer. You allocated 1 `struct utmp`, so the size of the underlying data is `1*sizeof(struct utmp)`. – Dustin Nieffenegger Feb 26 '19 at 22:10
  • 1
    @Kody Richardson - there are several problems in your sample code. I tried to break them down in a response, but somebody cut me off at the knees with downvotes. BASIC PROBLEM: "sizeof(ptr)" doesn't return the size of a struct, array or object - it merely returns the #/bytes in a "pointer" (often "4", for a 32-bit CPU). No: "free()" does NOT return ANYTHING. Look here: [man free](https://linux.die.net/man/3/free). Finally, no: you can't "realloc()" memory you've already free()'ed. Q: Questions answered? – paulsm4 Feb 26 '19 at 22:53
  • @paulsm4 Yes that clears many things up! Thank you! – Kody Richardson Feb 27 '19 at 23:00
  • @DustinNieffenegger Thank you for pointing out my error with the roster!! – Kody Richardson Feb 27 '19 at 23:01

0 Answers0