cfor-loopdynamic-memory-allocationreallocinvalid-pointer

realloc says invalid pointer unless unrelated for-loop commented out


Okay, I am very confused and desperately need help. I'm working on an assignment to dynamically allocate an array of strings, and I've been having trouble with realloc the entire time. I finally got it to the point where it seemed to be working, I just needed to write the for-loop to properly display the results.

Except then, the code would stop working. It'd let me put in the string, the exact same string I'd been using to test it before, and the program would crash saying that realloc was having an issue with an invalid pointer. Whenever I comment the for-loop out again, everything seems to be working just fine.

This is probably either something dumb or the result of something I don't understand about realloc, but I'm running out of time and various searches haven't returned any answers I think are applicable, so i figured I'd ask here.

The input I've been using to test it has been the line "hello my one true friend".

Here's my code (Yes, I know, it's a mess, sorry. Normally I'm a little better about these things but I've been in a very big hurry):

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int MAXSTRING = 255;

int makearg(char s[], char **args[]);

int main()
{
   char **tokenArray;
   char strInput[MAXSTRING];
   int tokenResult;
   int i = 0;

   printf("Input String to be Parsed: ");
   scanf("%[^\n]%*c", strInput);

   tokenResult = makearg(strInput, &tokenArray);

   printf("argc: %d\n", tokenResult);
   for (i < tokenResult; i++;)
   {
      printf("arg(%d): %s\n", i, tokenArray[i][1]);
   }
}

int makearg(char s[], char **args[])
{
   int numTokens = 0;
   int lastSpace = 0;
   int i = 0;
   char token[MAXSTRING];
   int subFromPos = 0;
   while ((s[i] != '\n') && (s[i] != '\0'))
   {
      token[i - lastSpace - subFromPos] = s[i];
      if (s[i] == ' ')
      {
         token[i - lastSpace] = '\0';
         *args = realloc(*args, (numTokens + 1));
         //printf("the seg fault hasnt happened yet 1\n");
         args[numTokens] = NULL;
         args[numTokens] = realloc(args[numTokens], (i - lastSpace + 1));
         //printf("the seg fault hasnt happened yet 2\n");
         *args[numTokens] = token;
         printf("Saved Token: %s\n", *args[numTokens]); //test to see if the token got written properly
         numTokens++;
         lastSpace = i;
         subFromPos = 1;
      }
      //printf("%c\n", s[i]);
      //printf("Token: %s\n", token);
      //printf("the seg fault hasnt happened yet\n");
      i++;
   }
   numTokens++;
   return numTokens;
}

Solution

  • You have not initialized tokenarray

    char **tokenArray;
    

    so when you call realloc on it you are invoking UB. the argument to realloc must either be NULL or a valid heap pointer. Do this

    char **tokenArray = NULL;
    

    and fix that for loop