gpt4 book ai didi

c - C 中 strcpy 的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:26 25 4
gpt4 key购买 nike

我有这个结构:

struct _window{
int bcolor; /* background color */
int fcolor; /* foreground color */
int x; /* x coordinate */
int y; /* y coordinate */
int sx; /* lenght */
int sy; /* high*/
char **matrix; /* Matrix with chars */
};

我用这个函数来初始化窗口

window* ini_window(int bcolor, int fcolor, int x, int y, int sx, int sy) {
window *v;
int i;

v = (window*) malloc(sizeof (window));
if (!v) /* CDE */
return NULL;

v->bcolor = bcolor;
v->fcolor = fcolor;
v->x = x;
v->y = y;
v->sx = sx;
v->sy = sy;

/* allocate the matrix */
v->matrix = (char**) calloc(sy, sizeof (char*));
if (!v->matrix) { /* CDE */
free(v);
return NULL;
}

/* allocate the rows */
for (i = 0; i < sy; i++) {

v->matrix[i] = (char*) calloc(sx + 1, sizeof (char));

if (!v->matrix[i]) { /* CDE */
free(v->matrix);
free(v);
return NULL;
}

v->matrix[i] = "\0"; /*<- delete this line to solve */
}
return v;

}

我尝试用那个函数加载矩阵

int cargar_matriz_file(window*v, char *nom_file) {
int i;
char aux[100];
FILE *pf;

if (!v)
return -1;
if (!v->matrix)
return -1;
pf = fopen(nom_file, "r");
if (!pf) /* CDE */
return -1;



for (i = 0; i < v->sy; i++) {
fgets(aux, v->sx, pf);
if (v->matrix[i]) {
strcpy(v->matrix[i], aux); /* <-segmentation fault here */
strtok(v->matrix[i], "\r\n");
}
}
fclose(pf);
return 0;
}

但是在 strcpy 的行中有一个错误,aux 有正确的长度并且分配了 v->matrix[i],会发生什么?

最佳答案

对我来说,好像您首先使用 malloc 来获取一些内存:v->matrix[i] = (char*) calloc(sx + 1, sizeof (char));然后通过将指针重新分配给常量字符串来泄漏该内存:v->矩阵[i] = "\0";写入此类指针的内容将产生段错误。

您可能想改为执行类似 sprintf 或 strcpy 的操作,或者可能只是:v->矩阵[i][0]=0;

关于c - C 中 strcpy 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com