误区
使用字符串误区,代码如下
误区1:
char *get_xx_version() {
int file_handle = open("/xxx/xxx.txt",O_RDONLY);
char *xxx = NULL;
int err = read(file_handle,xxx,8);
close(file_handle);
log_ota("ver = %s\n",xxx);
return xxx;
}
结果:ver = NULL
原因:NULL 代表一个不被使用的地址
误区2:
char *get_xx_version() {
int file_handle = open("/xxx/xxx.txt",O_RDONLY);
char *xxx = {"\0"};
int err = read(file_handle,(void*)xxx[0],8);
close(file_handle);
log_ota("ver = %s\n",xxx[0]);
return xxx[0];
}
结果:程序跑飞
原因:read(file_handle,(void*)xxx[0],8);给未定义的地址空间内赋值
误区3:
char *get_xx_version() {
int file_handle = open("/xxx/xxx.txt",O_RDONLY);
char *xxx[] = {"\0\0\0\0\0\0\0\0\0\0\0"};
int err = read(file_handle,(void*)xxx[0],8);
close(file_handle);
log_ota("ver = %s\n",xxx[0]);
return xxx[0];
}
结果:程序跑飞
原因:和误区2一个道理
误区4:
char *get_device_sw_version() {
int file_handle = open("/data/version.txt",O_RDONLY);
if (file_handle < 0) {
log_ota("open error\n");
}
char version[10] = {'\0'};
int err = read(file_handle,&version[0],8);
if (err <= 0) {
log_ota("read error\n");
}
close(file_handle);
log_ota("ver = %s\n",version);
log_ota("ver10 = %c\n",version[9]);
return &(version[0]);
}
结果:编译不过 报错 function returns address of local variable
原因:函数中的局部变量存放在stack中,函数执行完成之后会自动释放,因此不应将局 部变量的指针作为返回值。
可以使用 malloc 给局部变量申请内存,那么它是放在堆区,然后返回此变量就好了。另注意手动释放内存。