我正在与指针作斗争 :(。我尝试创建一个函数来执行类似于 argv 返回的操作。我的意思是,我希望它将一个订单分成一些字符串,每个字符串由不同的指针按顺序指向通过方括号引用它们。(即:order[0]、order[1])。
我想对任意数量的单词执行此操作,所以我使用动态内存。为了划分顺序,我使用 strtok 并且它可以正常工作。问题是处理指针:
结果** 我使用 realloc 为指向每个单词的指针保留内存,因此,当有标记时,我执行以下操作:
- 我增加结果的大小
- 我为指向 token 的指针保留内存
- 我分配 token
(停止 markdown freakout 的文本)
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char linea[] = "send UDP 4500 50";
char **resul=NULL;
int numTokens,conta2;
char *sep=" ";//character which divides the orders
int conta=0; //counter of the number of tokens found
char *saveptr,*token;
for(token=strtok_r(linea,sep,&saveptr); token!=NULL; token=strtok_r(NULL,sep,&saveptr)){
printf("token: %s\n",token);
printf("size: %i\n",(conta+1)*sizeof(char*));
resul = (char **)realloc(resul,(conta+1)*sizeof(char*)); //Increase the size for the array of pointers
resul[conta]= malloc(sizeof(char*)); //Reserve size for the pointer
resul[conta]=token; //Asign word to the pointer
conta++;
}
//Print the results
for(conta2=0;conta2<conta;conta2++)
printf("resul: \"%s\"\n",resul[conta2]);
//free memory
for(conta2=0;conta2<conta;conta2++){
printf("liberando: %i\n",conta2);
free(resul[conta2]);
}
free(resul);
return(0);
}
输出是:
$ ./lectura_consola
token: send
size: 4
token: UDP
size: 8
token: 4500
size: 12
token: 50
size: 16
resul: "send"
resul: "UDP"
resul: "4500"
resul: "50"
liberando: 0
*** glibc detected *** ./lectura_consola: free(): invalid pointer: 0xbffb7f1b ***
如果我用 valgrind 运行它以查看内存中的故障,在 free(resul[0]) 步骤中会发生:
liberando: 0
==8372== Invalid free() / delete / delete[]
==8372== at 0x40257ED: free (vg_replace_malloc.c:366)
==8372== by 0x80489FA: main (lectura_consola.c:92)
==8372== Address 0xbee8e28b is on thread 1's stack
使用这段代码,程序可以正确保存和打印单词,但在释放内存时它会利用它,当它试图释放 resul[0] 时说:无效指针。
你能告诉我错误在哪里吗?我完全迷路了,任何帮助都会有用
最佳答案
这里的问题是您试图释放您没有分配的内存。你的第一个循环中有这段代码:
resul[conta]= malloc(sizeof(char*)); //Reserve size for the pointer
resul[conta]=token; //Asign word to the pointer
第二条语句覆盖了第一条语句的结果,因此当您调用 free(resul[conta])
时,您正在尝试释放 token
(是指向字符串的指针)而不是您分配的指针。
在任何情况下您都不需要第一个语句。您的 realloc
调用为指针数组保留空间。对 malloc
的调用只是分配 sizeof(char*)
字节,效果不佳(即浪费内存)。由于该值只是被覆盖,您最终会泄漏该内存。
只需删除对 malloc
的调用,您的代码就可以正常工作。
关于c - 处理动态矩阵中的指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4370374/