0

I'm using the poll function. The library has a structure as so:

struct pollfd{
   int fd;
   short events;
   short revents;
}

Now, in my code I have an array of these events and I need to be able to realloc and give more memory space for more items. This is what I currently have:

#define NRCONNECTIONS 10
#define STEPSIZE 5

struct pollfd pollFd[NRCONNECTIONS];

int main(void){
   void * temp;
   temp = realloc((void *)pollFd, (sizeof(pollFd)/sizeof(pollFd[0])) + STEPSIZE);
   if(temp != NULL){
    pollFd = (struct pollfd *)temp;
   }
}

Now, I can't seem to get the code inside the if(temp != NULL) correct. I can't do it without a cast because then it's incorrect. I can't do it with a (struct pollfd) cast because that's non-scalar. Like this also isn't working. Is it because my pollFd variable is done without a malloc(), or is something else wrong?

Thanks in advance.

Update

struct pollfd *pollFd;

pollFd = malloc(NRCONNECTIONS * sizeof(struct pollfd));
if(pollFd == NULL){
    printf("Error malloc\n");
    fflush(stdout);
    exit(0);
}

This should be the correct initialization then? How do I then make it act like an array? I mean, how do I access eg the 0'th element?

Community
  • 1
  • 1
jdepypere
  • 3,453
  • 6
  • 54
  • 84
  • You can only realloc allocated memory. – this Jun 21 '14 at 15:29
  • And using the 'standard' method doesn't use a malloc behind the scenes? – jdepypere Jun 21 '14 at 15:30
  • @arbitter No, declaring a variable with static storage allocates it in the part of executable prepared by the operating system for this express purpose. Unlike the dynamic memory (also known as the "heap") returned by `malloc`, the memory region for static storage cannot grow and pointers to it cannot be passed to `free` and `realloc`. – user4815162342 Jun 21 '14 at 15:40

2 Answers2

2

The first argument of realloc must be a pointer that is earlier returned by a call to malloc, realloc or calloc, or a null pointer. In your case, it's not any of them.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • So the name of the array contains the address of the 0'th element, yet it isn't a pointer? – jdepypere Jun 21 '14 at 15:31
  • I'm not entirely clear on how I should then also be able to access it with indexes. – jdepypere Jun 21 '14 at 15:53
  • @arbitter It's certainly not a pointer that you have previously obtained by calling malloc/calloc or realloc, and therefore you cannot pass it to realloc. – nos Jun 21 '14 at 16:00
1

Its because pollFd is array type, so you cannot assign anything to it.

Change

struct pollfd pollFd[NRCONNECTIONS];

to

struct pollfd *pollFd;
Rohan
  • 52,392
  • 12
  • 90
  • 87
  • How do I make it behave like an array then? I thought doing `myArray = pollFd`, since `myArray` should contains the address of `myArray[0]`, being the starting point of the allocated block, but how do I initialize the `myArray` variable then? – jdepypere Jun 21 '14 at 16:01