【发布时间】:2015-05-11 05:44:43
【问题描述】:
我正在尝试使用一个结构来保存指向数据块的指针,我有时会在文件更新时更改该指针,其想法是释放旧数据块,分配一个合适大小的新数据块,然后分配指向结构中指针的指针指向malloc返回的指针,这就是我认为我应该这样做的方式。但它会出现故障。事实上,在我为制作这个测试程序而缩减的更大程序中,它不是段错误,而是在 malloc 之后写入 stdout 什么都不做(之后在程序中的任何地方)。我想我是在 stdout FD 上写的,原因是当我将指针设置为 malloc()ed 返回值时,我错误地使用了指针。
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <malloc.h>
#include <inttypes.h>
struct mystruct {
int offset;
int ** d;
};
int filecheck (struct mystruct *g, int * count) {
int v, size = 0;
FILE *f = fopen("/home/pi/schedule/default", "rb");
if (f == NULL) {
return 0;
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
int schedsize = sizeof(int);
int elementcount = size / schedsize;
// free(*(g->d));
// seg fault next line
if ((*(g->d) = malloc(size))==NULL) return 0;
if (elementcount != fread(*(g->d), schedsize, elementcount, f)) {
free(*(g->d));
return 0;
}
fclose(f);
*count = elementcount;
return 1;
}
void setp (struct mystruct *g) {
// if uncommented, seg fault here
// *(g->d) = NULL;
}
int main (){
struct mystruct g;
setp(&g);
int i, count = 0;
if (filecheck(&g, &count)==0) {
printf("Returned 0\n");
return 0;
}
while (1) {
printf("%d\n", (*(g.d))[i]);
sleep(1);
}
return 0;
}
为方便起见,我最初想在setp() 中将mystruct.d 设置为NULL,但即使注释掉代码仍然失败,所以我知道它完全错误。也许我不需要使用指向指针的指针,但在我看来我需要。
编辑:根据答案修改,可以吗?
struct mystruct {
int offset;
int * d;
};
int filecheck (struct mystruct *g, int * count) {
int v, size = 0;
FILE *f = fopen("/home/pi/schedule/default", "rb");
if (f == NULL) {
return 0;
}
fseek(f, 0, SEEK_END);
size = ftell(f);
fseek(f, 0, SEEK_SET);
int schedsize = sizeof(int);
int elementcount = size / schedsize;
free (g->d);
if ((g->d = malloc(size))==NULL) return 0;
if (elementcount != fread(g->d, schedsize, elementcount, f)) {
free(g->d);
return 0;
}
fclose(f);
*count = elementcount;
return 1;
}
void setp (struct mystruct *g) {
g->d = NULL;
}
int main (){
struct mystruct g;
setp(&g);
int i, count = 0;
if (filecheck(&g, &count)==0) {
printf("Returned 0\n");
return 0;
}
while (1) {
for (i=0;i<count;i++) {
printf("%d %d \n", *((g.d)+i), g.d[i]);
}
sleep(1);
}
return 0;
}
这似乎有效,但它是正确的,还是我写了一些我不应该再用这个写的内存?
【问题讨论】:
标签: c pointers struct malloc dynamic-memory-allocation