-3

Hi guys could you help me I am trying to get text from input and save it to string which size depends on input, so i allocated it but when i try to free that memory error appers i tried to debbug it but i stucked here. Without free() it ends normally, I tried on linux and it executed,but in visual studio problem appeared, should I be worried?

Debugger stucks on this /* * If this ASSERT fails, a bad pointer has been passed in. It may be * totally bogus, or it may have been allocated from another heap. * The pointer MUST come from the 'local' heap. */ _ASSERTE(_CrtIsValidHeapPointer(pUserData));

int unosUBuffer(char *tmpBuffer,int spaceCounter)
{
   int i = 0;
   int input = ' ';
  do 
  {
   input = getchar();

    if(input ==' ') 
    {
    spaceCounter ++; 
    }

    tmpBuffer = (char*)realloc(tmpBuffer,(sizeof(char))* i+1);
    tmpBuffer[i] = input;
    i++; 
  }while(tmpBuffer[i-1] != '\n');

   tmpBuffer[i-1] = '\0';
   return spaceCounter;
}

int main(int argc, char *argv[])
{
   int spaceCounter = 0;
   char *tmpBuffer;
   char *line;

   tmpBuffer = (char*)malloc(sizeof(char)); 
   welcomeScreen(); 
   spaceCounter = unosUBuffer(tmpBuffer, spaceCounter);
   printf("\n space counter = %d", spaceCounter);

   free(tmpBuffer);

   return 0;
}

Sry guys I pasted wrong code with wrong function names, functions unosUBuffer() and inputBuffer() is the same function, its unosUBuffer().

Sirke
  • 33
  • 8

1 Answers1

3

tmpBuffer in inputBuffer() may be changed by assigning the return value of realloc(), but main() won't know the new value and it tries to free where the old buffer was. The old buffer may already be freed by realloc(), and freeing it again may cause crash.

You should make the argument tmpBuffer a pointer to char*, and let main() know where the new buffer is.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 1
    `inputBuffer()` stil have the same risk when it is called from another function. – MikeCAT Feb 12 '16 at 22:39
  • @EOF While `inputBuffer()` is not called from main, `unosUBuffer()` is, and we don't know its definition. However, its signature is the same, and OP felt it relevant to post. If the two functions are the same, then switching the call to `unosUBuffer(&tmpBuffer, spaceCounter)`, the signature to `int inputBuffer(char **tmpBuffer, int spaceCounter)`, and the tmpBuffer reassignment to `*tmpBuffer = (char*)realloc(tmpBuffer,(sizeof(char))* i+1); (*tmpBuffer)[i] = input;` fixes the issue that was asked. – russianfool Feb 12 '16 at 22:42