gpt4 book ai didi

c - 释放内存(或分配)时出现问题

转载 作者:行者123 更新时间:2023-11-30 18:45:28 27 4
gpt4 key购买 nike

我收到一条“free():无效指针,中止(核心转储)”类型的消息,该消息可能会追溯到我正在执行的自由操作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char* ReadFile(char *filename)
{
char *buffer = NULL;
int string_size, read_size;
FILE *handler = fopen(filename, "r");

if (handler)
{
// Seek the last byte of the file
fseek(handler, 0, SEEK_END);
// Offset from the first to the last byte, or in other words,filesize
string_size = ftell(handler);
// go back to the start of the file
rewind(handler);

// Allocate a string that can hold it all
buffer = (char*) malloc(sizeof(char) * (string_size + 1) );

// Read it all in one operation
read_size = fread(buffer, sizeof(char), string_size, handler);

// fread doesn't set it so put a \0 in the last position
// and buffer is now officially a string
buffer[string_size] = '\0';

if (string_size != read_size)
{
// Something went wrong, throw away the memory and set
// the buffer to NULL
free(buffer);
buffer = NULL;
}

// Always remember to close the file.
fclose(handler);
return buffer;
}

return NULL;
}
int newLineCounter(char *string)
{
if(string==NULL)
return -1;
int count=0;
for(int i=0;((string[i])!='\0');i++)
{
if(string[i]=='\n')
count++;
}
return count;
}

char ** arrayOfWords(char *str,int max)
{
char **s;
s=malloc(max*(sizeof(char *)+1));
if(str==NULL||max<0)
return NULL;
int count=0;
char *temp=strtok(str,"\n");
int size=strlen(temp);
s[0]=malloc((sizeof(char *)*(size+1)));
s[0]=temp;
// int count=0;
while((s!=NULL)&&(count<max-1))
{
count++;
char *temp=strtok(NULL,"\n");
int size=strlen(temp);
s[count]=malloc((sizeof(char *)*(size+1)));
s[count]=temp;
}
count++;
s[count]="\0";

return s;
}




int main()
{
char *string = ReadFile("hi.txt");
if(string==NULL) {
printf("%s\n","Error,no files here" );
}
else {


int newLines=newLineCounter(string);
char **ret=arrayOfWords(string,newLines);
for(int i=0;i<newLines;i++)
{
printf("%s\n",ret[i] );
}
for(int i=0;i<newLines;i++)
{
free((ret[i]));
}

free(ret);

}
return 0;
}

因此,我在 arrayOfWords 函数中为每个由换行符分隔的“单词”分配内存。在主函数中打印所有单词后,我首先尝试释放分配给每个单词的内存,然后希望释放指针本身。当我尝试在 gdb 中调试它时,我在 for 循环中设置了一个断点,我试图释放每个引用。我在第二次迭代期间得到一个 SIGABRT,我很困惑为什么会发生这种情况。因此,当我尝试在 for 循环中释放内容并且在释放实际指针之前,就会发生错误。

干杯。

最佳答案

您在函数 char ** arrayOfWords(char *str,int max) 中使用 malloc 时遇到问题

1> 对于函数 char ** arrayOfWords(char *str,int max) 内的双指针 **s

s=malloc(max*(sizeof(char *)+1));

应该是

s=malloc(max*sizeof(char *));

因为 s 是一个指向 char 指针数组的指针。

2> 对于 **s 内的每个项目。

s[0]=malloc((sizeof(char *)*(size+1)));
s[count]=malloc((sizeof(char *)*(size+1)));

他们应该是

s[0]=malloc((sizeof(char)*(size+1));
s[count]=malloc((sizeof(char)*(size+1)));

因为 s[i] 现在是一个指向字符数组的指针。

关于c - 释放内存(或分配)时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54798176/

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