realloc和自由原因"双重自由或腐败"

Joh*_*oer 0 c free corruption realloc segmentation-fault

忍受我.我在8年内没有用c编码,我完全不知道为什么我的字符串操作不起作用.我正在写一个永远循环的程序.在循环中,我初始化两个char指针,每个指针都传递给一个向char指针(数组)添加文本的函数.函数完成后,我打印char指针并释放两个char指针.但是,程序在7次迭代后死亡,并显示以下错误消息

*glibc检测到* ./test:双重免费或损坏(fasttop):0x0804a168***

#include sys/types.h
#include sys/stat.h
#include fcntl.h
#include string.h
#include stdio.h
#include stdlib.h
#include errno.h
#include time.h

char *SEPERATOR = "|";

void getEvent (char* results);
void getTimeStamp(char* timeStamp, int timeStampSize);
void stringAppend(char* str1, char* str2);

int main (int argc, char *argv[])
{
  int i = 0; 
  while(1)
  { 
    i++;
    printf("%i", i);    

    char* events= realloc(NULL, 1); 
    events[0] = '\0';
    getEvent(events);

    char* timestamp= realloc(NULL, 20);
    timestamp[0] = '\0';
    getTimeStamp(timestamp, 20);

    printf("%s", events);
    printf("timestamp: %s\n", timestamp);

    free(events);
    free(timestamp);
  } 
}

void getEvent (char* results)
{
  stringAppend(results, "a111111111111");
  stringAppend(results, "b2222222222222");
}

void getTimeStamp(char* timeStamp, int timeStampSize)
{
  struct tm *ptr;
  time_t lt;
  lt = time(NULL);
  ptr = localtime(&lt);
  int r = strftime(timeStamp, timeStampSize, "%Y-%m-%d %H:%M:%S", ptr);
}

void stringAppend(char* str1, char* str2)
{   
  int arrayLength = strlen(str1) + strlen(str2) + strlen(SEPERATOR) + 1;
  printf("--%i--",arrayLength);

  str1 = realloc(str1, arrayLength);
  if (str1 != NULL)
  {
    strcat(str1, SEPERATOR);
    strcat(str1, str2);
  }
  else
  {
    printf("UNABLE TO ALLOCATE MEMORY\n");
  }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*tis 7

您正在重新分配str1但不将值传递出函数,因此可能更改的指针会被泄露,并且已释放的旧值realloc将再次被您释放.这导致"双重免费"警告.