c - 返回主函数指针时数据被重置 c/linux

标签 c pointers

仍未修复添加的新代码

我在linux中使用c来完成我的类(class),我遇到了指针问题,因为我设法将数据存储在指针中,但当它返回到主函数时,它已被重置。我很困惑,因为它的行为就像一个常规变量

谁能帮我保留功能完成后的数据

我尝试了下面的解决方案,但新的我遇到了段错误

#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

//defines
#define BUFFSIZE 1000000
#define PROCS 2

//prototypes
void read_file(char *filename,  char** buffer);

/* The name of this program. */
const char* program_name;


int main (int argc, char* argv[]){
//records keystroke
    int next_option;
//records values
    int print_chars = 0, print_words = 0, print_lines = 0;
    char* fileName = "/usr/share/dict/words";
    char* buffer;
    char** ptb = &buffer;
    int check;
/* designates options
     -h --help Display this usage information. 
     -n --num Display my student number. 
     -c --chars Print number of characters in FILENAME. 
     -w --words Print number of words in FILENAME. 
     -l --lines Print number of lines in FILENAME. 
     -f --file FILENAME Read from file. 
*/
    const char* const short_options = "f:";
    const struct option long_options[] = {
        { "file", 1, NULL, 'f' },
        { NULL, 0, NULL, 0 }};
//calls functions when the keys are pressed
    do {
        next_option = getopt_long (argc, argv, short_options,
        long_options, NULL);
        switch (next_option){
            case 'f': /* -f or --file */
                fileName = optarg;
                read_file (fileName, ptb);
                printf("%s\nreturned\n", buffer);   
                check = 1;          
                break;
            case '?': /* The user specified an invalid option. */
                check = 1;
            case -1: /* Done with options. */
                if(!check){
                    if(!buffer[0]){
                        read_file (fileName, ptb);
                    }
                    printf("No command was entered so default :\n");
                }
                break;
            default: /* Something else: unexpected. */
                abort ();
        }
    }while (next_option != -1);
}
void read_file (char *file, char** buffer){
    FILE    *fp = fopen(file, "r"); //file that is being read
    long    numbytes;
    int len = 0;

//quit if file doesn't exist
    if(fp == NULL){
        printf("File not found at: %s\n", file);
        return;
    } 

    fseek(fp, 0L, SEEK_END); //goes to end of file
    numbytes = ftell(fp);   // Get the number of bytes
    fseek(fp, 0L, SEEK_SET);    //goes to beginning of file
    numbytes = numbytes + sizeof(char);
    *buffer = (char*)calloc(numbytes, sizeof(char));//allocates memory
    len = fread(*buffer, sizeof(char), numbytes, fp);// copy all the text into the buffer

    if(len == 0){
        printf("Write to memory error\n");
        return;
    }
        *buffer[++len] = '\0';//put end terminater in
    fclose(fp);         
    printf("%s\n", *buffer);

    printf("File location :%s\n", file);
    return;
}

最佳答案

您的内存管理已关闭。您在 main 中创建 buffer[BUFFSIZE] 并将指向该区域的指针传递给您的函数,但在您的函数中,您使用 calloc 分配另一个内存区域,您将文件读入其中,但指向该区域的指针不会返回到 main。 您应该删除 main 中的缓冲区变量,并让 readFile 返回从 calloc 收到的指针。例如。您可以将函数原型(prototype)更改为:

 void read_file (char *file, char** buffer);

当你使用 calloc 时,你会这样做

 *buffer = calloc(...);

(缓冲区的以下使用将需要适当的取消引用。

此外,我认为您访问了无效内存。您检查文件中有多少字节并分配那么多内存,然后读取所有这些字节。但最终你会这样做:

 buffer[++len] = '\0';

如果我没记错的话,访问的字节超出了分配的内存区域。

关于c - 返回主函数指针时数据被重置 c/linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457142/

相关文章:

c - 函数指针的指针值代表什么?

c - 了解 fread() 以存储 rgb 像素值

C++:如何获取浮点指针的地址并将其转换为 void**

CMAKE - 如何正确地将静态库的头文件复制到/usr/include?

c - 文件处理中的意外输出

c - C 中链表的简单实现 错误答案

c++ - 在这里出现 'sigbrt'错误的原因是什么?

c - 当我添加代码来设置路径并想要检索文件(在我的程序中选择2)时,它将显示段错误(核心转储)

c - 交换函数中的二维数组引用

c - "error: subscripted value is neither array nor pointer nor vector",但为什么呢?