Reputation: 13
so I have spent some hours trying to figure out why my realloc doesnt enlarge my array of structs, but I seem to make no progress. Realloc either fails or doesnt enlarge the array. Is there any obvious mistake that Im making?
#include <getopt.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct fileInfo {
char accessRights[12];
short hardLinks;
short userName;
short groupName;
long size;
char *time;
char *fileName;
short nrOfNode;
} fileInfo;
void enlargeFileInfos(fileInfo *fileInfoArray, int currentSize)
{
fileInfo *temp = (fileInfo*)realloc(fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (!temp) {
printf("realloc --FAILED--\n");
return;
}
fileInfoArray = temp;
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
}
int main( )
{
size_t nrOfDirs = 1;
fileInfo *fileInfoArr = malloc(sizeof(fileInfo));
for (int i = 0; i < 5; i++) {
enlargeFileInfos(fileInfoArr, nrOfDirs);
nrOfDirs++;
}
return 0;
}
Upvotes: 1
Views: 65
Reputation: 937
To realloc
memory on which fileInfoArray
points to inside enlargeFileInfos
, you have to pass its address to the function:
void enlargeFileInfos(fileInfo **fileInfoArray, int currentSize)
{
fileInfo *temp = realloc(*fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (temp == NULL) {
printf("realloc --FAILED--\n");
return;
}
*fileInfoArray = temp;
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
}
Then you call the function in this way:
enlargeFileInfos(&fileInfoArr, nrOfDirs);
As pointed by Jonathan Leffler in comments, an alternative way is to return the realloc
ed memory from the function enlargeFileInfos
:
fileInfo *enlargeFileInfos(fileInfo *fileInfoArray, int currentSize)
{
fileInfo *temp = realloc(fileInfoArray, (currentSize + 1) * sizeof(fileInfo));
if (temp == NULL) {
printf("realloc --FAILED--\n");
return NULL;
}
printf("fileInfo grew to %d item(s)\n", currentSize + 1);
return temp;
}
And than, you use it this way:
fileInfoArr = enlargeFileInfos(fileInfoArr, nrOfDirs);
if (fileInfoArr == NULL) {
/* Handle allocation failure */
}
And after you finish working with fileInfoArr
, don't forget to free it:
free(fileInfoArr);
I have removed the cast from realloc
, so take a look on Do I cast the result of malloc?, and change the signature of main
to int main(void)
.
Upvotes: 1