时间变量必须定义为static&循环保存删除最新日期数据的问题

#include <stddef.h>
#include <time.h>
static char *getSystemTime(void)
{
    struct timespec time;
    struct tm nowTime ;
    char currentTime[50];
    clock_gettime(CLOCK_REALTIME, &time);//get seconds from 1970
    localtime_r(&time.tv_sec, &nowTime);//get year month day hours min sec
    sprintf(currentTime, "%04d/%02d/%02d %02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon+1, nowTime.tm_mday, nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);
    printf("%s\n",currentTime);
    return currentTime;
}

int main()
{
 char *temp = NULL;
 temp = getSystemTime();
 printf("%s\n",temp);
}

运行结果

2018/09/15 21:19:39
Segmentation fault (core dumped)

这是因为currentTime是局部变量,被分配在栈区,当函数getSystemTime运行完之后程序就销毁了,销毁了但是还是会return变量地址的,只要return的这个地址不是栈区的就是可以使用的。只是变量所指向的内容销毁了,要么是乱码,要么是个不确定的值。但是你还是要打印这个地址,这就是错误的了。所以一定要记住,千万不要返回栈区的地址值。

修改方法是要么在变量前加个static让它分配在静态区,要么是申请一个内存空间,让它分配在堆区。

那么我们再看下面这个程序,

#include <stddef.h>
#include <time.h>
#include <string.h>

static char *getSystemTime(void)
{
    struct timespec time;
    struct tm nowTime ;
     static char currentTime[50];
    clock_gettime(CLOCK_REALTIME, &time);//get seconds from 1970
    localtime_r(&time.tv_sec, &nowTime);//get year month day hours min sec
    sprintf(currentTime, "%04d/%02d/%02d %02d:%02d:%02d", nowTime.tm_year + 1900, nowTime.tm_mon+1, nowTime.tm_mday, nowTime.tm_hour, nowTime.tm_min, nowTime.tm_sec);
    printf("%s\n",currentTime);
    printf("%p\n",currentTime);
    return currentTime;
}
static char *getFileName(void)
{
  char *dest = getSystemTime();
  const char *fileFormat = ".h264";
  printf("%s\n",dest);
  printf("%p\n",dest);
  strcat(dest, fileFormat);
  printf("%p\n",dest);
  return dest;
}


int main()
{
 char *temp = NULL;
 temp = getFileName();
 printf("%p\n",temp);
 printf("%s\n",temp);
}

那么这个程序为什么就是可以的呢,我们可能认为getFileName()函数返回的也是栈区的数据,但是其实不是,我们先打印一下地址,我们知道currentTime 定义为static的,是在全局区的,其实getFileName()函数里的dest只是将地址指向了全局区,并没有重新分配一个栈区的地址,所以我们看到的后面打印的地址都是一样的,它是不会将全局区的地址所指向的数据拷贝到栈区来的,同样的定义的fileFormat是个常量,它也是在全局区的。我们要清楚的了解你所申请的内存空间到底是堆还是栈还是全局区,main函数申请的也是在栈区。栈是先进后出。

2018/09/15 21:51:44
0x6010a0
2018/09/15 21:51:44
0x6010a0
0x6010a0
0x6010a0
2018/09/15 21:51:44.h264

之前遇到在循环保存中,定义了一个指针数组用来存储日期,其实数组里的元素地址都是指向的一个内存空间,就是那个currentTime这个全局变量的地址,所以才导致每次要删除都是删除最新日期的文件。解决办法就是将每次得到的数据都放到全局区,也就是定义一个字符串变量,然后再将这个字符串变量存储到数组中去。

常量区的数据不可以进行修改,这段空间是被内存区域所保护的一段区域

char *p = "ssaagd";

*(p+2) =‘m’;

这是不对的。会出错,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值