C段错误
所以我有这段代码C段错误,c,arrays,segmentation-fault,realloc,C,Arrays,Segmentation Fault,Realloc,所以我有这段代码 int main(int argc, char *argv[]) { char *vendas[1]; int size = 1; int current = 0; char buffer[50]; char *token; FILE *fp = fopen("Vendas_1M.txt", "r"); while(fgets(buffer, 50, fp)) { token = strtok(buffe
int main(int argc, char *argv[]) {
char *vendas[1];
int size = 1;
int current = 0;
char buffer[50];
char *token;
FILE *fp = fopen("Vendas_1M.txt", "r");
while(fgets(buffer, 50, fp)) {
token = strtok(buffer, "\n");
if (size == current) {
*vendas = realloc(*vendas, sizeof(vendas[0]) * size * 2);
size *= 2;
}
vendas[current] = strdup(token);
printf("%d - %d - %s\n", current, size, vendas[current]);
current++;
}
}
事情是这样的。。。使用GDB,它会在
vendas[current] = strdup(token);
但最奇怪的是,它一直工作到1024
。大小增加到1024
,然后在1200个元素附近出现分段错误。
我知道问题出在内存重新分配上,因为当我有一个静态数组时,它就起作用了。只是不知道是什么。在
char*vendas[1]
数组中,您只有一(1)个指针的空间。所以第二次你在数组的限制之外,并且在未定义的行为范围内
另外,对
realloc
的第一次调用传递了一个未由malloc
分配的指针,因此存在另一个未定义的行为。您无法重新分配本地数组,您希望vendas
成为指向已分配指针数组的指针:char**vendas=NULL代码>
您还应该包括正确的头文件,并检查fopen()
和realloc()
故障
以下是修改后的版本:
#include <stdio.h>
#include <stdlib.h>
void free_array(char **array, size_t count) {
while (count > 0) {
free(array[--count]);
}
free(array);
}
int main(int argc, char *argv[]) {
char buffer[50];
char **vendas = NULL;
size_t size = 0;
size_t current = 0;
char *token;
FILE *fp;
fp = fopen("Vendas_1M.txt", "r");
if (fp == NULL) {
printf("cannot open file Vendas_1M.txt\n");
return 1;
}
while (fgets(buffer, sizeof buffer, fp)) {
token = strtok(buffer, "\n");
if (current >= size) {
char **savep = vendas;
size = (size == 0) ? 4 : size * 2;
vendas = realloc(vendas, sizeof(*vendas) * size);
if (vendas == NULL) {
printf("allocation failure\n");
free_array(savep, current);
return 1;
}
}
vendas[current] = strdup(token);
if (vendas[current] == NULL) {
printf("allocation failure\n");
free_array(vendas, current);
return 1;
}
printf("%d - %d - %s\n", current, size, vendas[current]);
current++;
}
/* ... */
/* free allocated memory (for cleanliness) */
free_array(vendas, current);
return 0;
}
#包括
#包括
无空数组(字符**数组,大小\u t计数){
而(计数>0){
空闲(数组[--count]);
}
自由(数组);
}
int main(int argc,char*argv[]){
字符缓冲区[50];
char**vendas=NULL;
大小\u t大小=0;
电流大小=0;
字符*令牌;
文件*fp;
fp=fopen(“Vendas_1M.txt”,“r”);
如果(fp==NULL){
printf(“无法打开文件Vendas_1M.txt\n”);
返回1;
}
而(fgets(缓冲区、缓冲区大小、fp)){
令牌=strtok(缓冲区“\n”);
如果(当前>=大小){
char**savep=vendas;
大小=(大小==0)?4:大小*2;
vendas=realloc(vendas,尺寸(*vendas)*尺寸);
if(vendas==NULL){
printf(“分配失败\n”);
自由_数组(保存,当前);
返回1;
}
}
vendas[当前]=标准备份(令牌);
if(vendas[当前]==NULL){
printf(“分配失败\n”);
自由_阵列(vendas,当前);
返回1;
}
printf(“%d-%d-%s\n”),当前,大小,vendas[current]);
电流++;
}
/* ... */
/*可用分配内存(用于清洁)*/
自由_阵列(vendas,当前);
返回0;
}
@chqrlie这不是应该使用的realloc()
。如果重新分配失败,则会丢失原始指针并泄漏内存。建议T*tmp=realloc(ptr,大小);如果(!tmp){free(ptr);/*whatever*/}ptr=tmp
另外(我相信您知道这一点)变量应该声明/定义为尽可能接近它们的使用位置。@Swardfish:好的,我会更新代码,但在这种情况下,重新分配失败是一个致命错误,程序退出,所有分配的内存都返回到系统。您可以通过另一种方式检查大小,除此之外,它是完美的!谢谢