我目前正在尝试修复项目中遇到的问题。我必须将文件(地图)的内容读入矩阵,但第一行包含4个单独的字符:
代码:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include "head.h"
#define BUF_S 4096
char **ft_build_martrix(char *str, int *pr, int *pc, char *blocks)
{
int fd;
int ret;
int ret2;
int j;
char *res[BUF_S + 1];
j = 0;
fd = open(str, O_RDONLY);
if (fd == -1)
{
ft_putstr("map error");
}
ret2 = read(fd, blocks, 4); //take the first row out and put it into the array
ret = read(fd, res, BUFF_S); //read the file's content into the matrix
res[ret][0] = '\0';
*pr = blocks[0] - '0'; // give the number of rows to the r variable that is declared in main and passed as argument, I think that's the equivalent of the $r in c++ ?
blocks[0] = blocks[1]; // delete the
blocks[1] = blocks[2]; // first character
blocks[2] = blocks[3]; // that is already in *pr
while (res[1][j] != '\n')
j++;
*pc = j; // get the number of column
return (res);
}
答案 0 :(得分:0)
您正在返回指向本地变量的指针。从函数返回后,局部变量从范围中移除(它们的生命周期已经结束),因此访问该地址(不再属于您)具有未定义的行为。
这也是指向数组
的声明char * res[BUF_S + 1];
+---+ +---+
| * |--------->| | res[0][0] (*ret)[0]
+---+ +---+
res | | res[0][1]
+---+
| | ...
+---+
| | res[0][BUF_S + 1 - 1]
+---+
如果您应用此操作
res[ret][0] = '\0';
使用ret != 0
,您正在调用未定义的行为。
你必须像这样声明它(指向指针的指针)
char ** res = malloc(sizeof(char*) * X); // Where X is number of rows
每一行分别
for (int i = 0; i < X; i++)
{
res[i] = malloc(BUF_S + 1);
}
然后,您可以访问不同的“行”(最大X-1
,X
,更多会再次导致访问边界和未定义的行为。
然后你将释放记忆。