0

I'm just trying to malloc an array of strings and copy input from a file into this array. This combination of lines causes a segfault and I don't know why.

int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input);
slmyers
  • 767
  • 1
  • 8
  • 21
  • Don't cast malloc: http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – Barmar Oct 10 '13 at 16:56

3 Answers3

5

You've allocated space for an array of pointers, but you haven't initialized any of those pointers.

int count = 0;
char **output = malloc(numLines*sizeof(char *));
int i;
for (i = 0; i < numLines; i++) {
  output[i] = malloc(257);
}
fgets(output[count], 257, input);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

I think what you actually wanted to do here was allocate a memory for numLines pointers (strings) and then allocate memory for every string so that each of these is capable of holding 257 chars:

int i, count = 0;
char **output = malloc(sizeof(char*) * numLines);
for (i = 0; i < numLines; ++i)
    output[i] = malloc(257);
...
fgets(output[count], 257, input);

just don't forget to clean it up once you don't need it anymore:

for (i = 0; i < numLines; ++i)
    free(output[i]);
free(output);
output = NULL;
LihO
  • 41,190
  • 11
  • 99
  • 167
1
int count = 0;
char **output = (char**)malloc(numLines*257);
fgets(output[count], 257, input); // here You are going wrong, with out allocating memory you are trying to read.

if you want to read string

char *output = malloc(MAX_LENGTH+1); //allocate memory
    fgets(output[count], MAX_LENGTH+1, input);

if you want to read array of strings

char **output = malloc(MAX_NUM_STRINGS * sizeof(char *)); //allocate Number of pointers 
for(count=0;count<MAX_NUM_STRINGS;count++)
{   output[count]=malloc(SIZE_OF_EACH_STRING+1);  //allocate memory for each pointer,  
    //You are accessing with out allocating memory  
    fgets(output[count], SIZE_OF_EACH_STRING+1, input); 
}
Gangadhar
  • 10,248
  • 3
  • 31
  • 50