c - Malloc 不断返回相同的指针

标签 c pointers malloc

我有一些 C 代码来解析一个文本文件,首先逐行然后转换为标记

这是逐行解析它的函数:

int parseFile(char *filename) {
//Open file
FILE *file = fopen(filename, "r");
//Line, max is 200 chars
int pos = 0;
while (!feof(file)) {
    char *line = (char*) malloc(200*sizeof(char));
    //Get line
    line = fgets(line, 200, file);
    line = removeNewLine(line);
    //Parse line into instruction
    Instruction *instr = malloc(sizeof(instr));
    instr = parseInstruction(line, instr);
    //Print for clarification
    printf("%i: Instr is %s arg1 is %s arg2 is %s\n", 
        pos,
        instr->instr,
        instr->arg1,
        instr->arg2);
    //Add to end of instruction list
    addInstruction(instr, pos);
    pos++;
    //Free line
    free(line);
}
return 0;

这是将每一行解析为一些标记并最终将其放入指令结构的函数:

Instruction *parseInstruction(char line[], Instruction *instr) {
//Parse instruction and 2 arguments
char *tok = (char*) malloc(sizeof(tok));
tok = strtok(line, " ");
printf("Line at %i tok at %i\n", (int) line, (int) tok);
instr->instr = tok;
tok = strtok(NULL, " ");
if (tok) {
    instr->arg1 = tok;
    tok = strtok(NULL, " ");
    if(tok) {
        instr->arg2 = tok;
    }
}
return instr;

printf("Line at %i tok at %i\n", (int) line, (int) tok); 在 ParseInstruction 中总是打印相同的两个值,为什么这些指针地址永远不会改变?我已经确认 parseInstruction 每次都返回一个唯一的指针值,但是每条指令在它的 instr 槽中都有相同的指针。

为了清楚起见,指令定义如下:

typedef struct Instruction {

char *instr;
char *arg1;
char *arg2;

} 说明;

我做错了什么?

最佳答案

就是这样strtok有效:它实际上修改了它正在操作的字符串,将分隔符替换为 '\0'并返回指向该字符串的指针。 (参见 the "BUGS" section in the strtok(3) manual page ,虽然它不是真正的错误,只是人们通常不会期望的行为。)所以你的初始 tok将始终指向 line 的第一个字符.

顺便说一下,这个:

char *tok = (char*) malloc(sizeof(tok));
tok = strtok(line, " ");

第一套tok指向 malloc 的返回值, 然后重新分配它指向 strtok 的返回值,从而完全丢弃 malloc 的返回值.就像这样写:

int i = some_function();
i = some_other_function();

完全丢弃 some_function() 的返回值;除了它更糟,因为丢弃了 malloc 的返回值结果 memory leak .

关于c - Malloc 不断返回相同的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13676559/

相关文章:

c++ - 基本 C++ 函数指针和结构

C 二维数组内存分配

c++ - 段错误 : 11 and malloc errors in C++ code

c++ - 如何为数组结构的数组分配内存

java - 在 Android ndk 的 C 库中测试异常处理程序

c - 卢阿C : How would I use the Lua source code to create a Lua interpreter that will execute given blocks of Lua code?

c - 在 C 中使用堆栈

c++ - 什么时候使用空指针?

c - 在 C 中将字符串添加到文本文件

c - 在使用局部变量的 C 分配/取消分配内存中哪个更好?为什么?