0

I have problem with realloc. This is my function which reads words from output and is terminated if EOF is detected. The function makes memory leaks and the following program throws SIGSEGV or SIGABORT. What's a problem ?

int inx=0;
char **wordList=NULL;

int v;
char tmpArr[100];

do
{
  v=scanf("%s",tmpArr);
  if(v!=-1)
  {
    char* word=(char*)malloc(strlen(tmpArr)+1);
    strcpy(word,tmpArr);
    char**more=(char**)realloc(wordList,sizeof(char*)*(inx+1));
    if(more!=NULL) {wordList=more;} else return 1;
    wordList[inx++]=word;
    printf("%d\n",inx);
  }
}
Peter Miehle
  • 5,984
  • 2
  • 38
  • 55
user1890078
  • 207
  • 1
  • 2
  • 7
  • 1
    Have you used a debugger or added extra `printf` statements to find which line your program fails on? Is there a missing `while` statement at the end of your code sample? – simonc Dec 14 '12 at 09:43
  • Are you sure there are no words to be read, that are larger than 99 characters? – alk Dec 14 '12 at 10:10
  • Do add error checking to malloc. Do not cast malloc nor realloc. – alk Dec 14 '12 at 10:15

1 Answers1

1
v=scanf("%s",tmpArr); 

the above can cause a memory overwrite if input string is larger than 100. you may want to use fgets(tmpArray,sizeof(tmpArray),stdin) instead to limit the input to max buffer size (or use scanf_s).

you should not cast what malloc returns, it returns a void* which doesn't need to be cast, if you cast you could mask an error if you forget to include stdlib.h

char* word = /* (char*) */ malloc(strlen(tmpArr)+1);

growing the array everytime you read a new string is not very effective, instead consider allocating a bunch of string pointers or preferably use another data structure e.g. a list

e.g.

if ( inx == maxindex  )
{
  char**more=(char**)realloc(wordList,sizeof(char*)*(maxindex + bunch));

  if (more != NULL) 
  {
    wordList = more;
    maxindex += bunch ;
  } 
  else 
  { 
    return 1;
  }
}

...

AndersK
  • 35,813
  • 6
  • 60
  • 86