Reputation: 21
I am working on a homework assignment that requires the creation of a dynamically allocated array which is to be populated with strings from a text file. I then need to print the array to standard output, shuffle the array, and then print it again.
My current issue is that I cannot seem to populate the array with anything without getting a segmentation fault. I tested the program with a static array and everything worked, so I know there isn't an issue with any of the other code.
Here is a section of my program.
void alloc2dArray(char ***source, int dim1, int dim2)
{
int i = 0;
source = malloc(sizeof(char *) * dim1);
if(source == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
for(i = 0; i < dim1; i++)
{
source[i] = malloc(sizeof(char) * (dim2 + 1));
if(source[i] == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
}
}
EDIT:
In an effort to avoid being a Three Star Programmer I changed my code to the below snippet. As luck would have it, that fixed my issue. So thanks to Kniggug for posting the link to something I had no idea about before.
char** alloc2dArray(int dim1, int dim2)
{
int i = 0;
char **twoDArray = malloc(sizeof(char *) * dim1);
if(twoDArray == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
for(i = 0; i < dim1; i++)
{
(twoDArray[i]) = malloc(sizeof(char) * (dim2 + 1));
if(twoDArray[i] == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
}
return twoDArray;
}
Thank you.
Upvotes: 1
Views: 364
Reputation: 3324
Change source
to (*source)
in alloc2dArray
Void alloc2dArray(char ***source, int dim1, int dim2)
{
int i = 0;
*source = malloc(sizeof(char *) * dim1);
if(*source == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
for(i = 0; i < dim1; i++)
{
(*source)[i] = malloc(sizeof(char) * (dim2 + 1));
if((*source)[i] == NULL)
{
printf("Memory full!");
exit(EXIT_FAILURE);
}
}
}
Upvotes: 1
Reputation: 97948
Void alloc2dArray(char ***source, int dim1, int dim2)
{
int i = 0;
source = malloc(sizeof(char *) * dim1);
The assignment above has no effect outside this function, apart from leaking memory. You mean to do:
*source = malloc(sizeof(char *) * dim1);
similarly:
(*source)[i] = malloc(sizeof(char) * (dim2 + 1));
Upvotes: 4