user3312266
user3312266

Reputation: 189

C - list of char*'s - Memory Allocation

I am confused about how to allocate memory correctly. I am trying to make a list of char*'s from a text file. Every time I make a char* do I have to allocate memory for it? When and where are the exceptions?

#define BUFF 1000   

 int main(int argc, char** argv)
 {
  FILE* file;
    file = fopen(argv[1], "r");
    char* word = calloc(BUFF, sizeof(char));
    char* sentence = calloc(BUFF, sizeof(char));
    char** list = calloc(BUFF, sizeof(char*));
    int i = 0;
while((fgets(sentence, BUFF, file)) != NULL)
{
  word = strtok(sentence, " ,/.");
  while(word != NULL)
  { 
    printf("%s\n", word);
    strcpy(list[i],  word);
    i++;
    word = strtok(NULL, " ,/.");
  } 
}
int k;
for(k = 0; k < i; k++)
{
 puts("segging here");
 printf("%s\n", list[i]);
}

Upvotes: 0

Views: 149

Answers (3)

Liu Hao
Liu Hao

Reputation: 512

your list is a char* list, with the size of BUFF, but the list[i] is what? you do not allocate memory to it.

you need to allocate the memory for list[i] in a loop

Upvotes: 0

Chris Culter
Chris Culter

Reputation: 4556

In addition to Matt McNabb's answer, there's also a more subtle problem with your usage of strtok. That function doesn't require an output buffer; it just returns a pointer to somewhere inside the input buffer.

When you call char* word = calloc(BUFF, sizeof(char));, you allocate memory and assign word to point to the allocated memory. Then, when you call word = strtok(sentence, " ,/.");, you overwrite the value of word. That means that no pointer in your control points to the memory you've allocated. That memory is no longer useful to your code, and you can't deallocate it; it has been leaked.

You can fix this issue by writing char* word = strtok(sentence, " ,/."); Then, since you didn't allocate the memory that word points to, remember not to free it either.

Upvotes: 0

M.M
M.M

Reputation: 141554

The rule is: you have to allocate any memory that you use.

Your problem comes in:

strcpy(list[i],  word);

list[i] is currently not pointing to any allocated storage (it's probably a null pointer). You have to make it point somewhere before you can copy characters into it.

One way would be:

list[i] = strdup(word);

strdup is not an ISO C standard function, but it is equivalent to doing malloc then strcpy. You will need to free afterwards.

Also, the i++ line needs to stop when i == BUFF, and it'd be useful to add \n to the list of strtok separators .

Upvotes: 3

Related Questions