Valgrind C中的错误,,条件跳转或移动取决于未初始化的值“”/,即使它们已初始化

t9eec4r0  于 2023-04-29  发布在  其他
关注(0)|答案(1)|浏览(135)
//#include "rand_malloc.h"
#include <stdio.h>
#include <stdlib.h>
#define SPACE 32
#define ENTER 13
#define STOP 10

int shouldRead = 1;
char** text;
char* newline;
char* crln;
int text_size = 1;

void clearMemory()
{
    for (int i = 0; i < text_size - 1; i++) {
        free(text[i]);
        text[i] = NULL;
    }
    free(text);
}

void clearMemoryError()
{
    for (int i = 0; i < text_size - 1; i++) {
        free(text[i]);
        text[i] = NULL;
    }
    free(text);
    free(crln);
    exit(0);
}

void checkSinglePointer(char* ptr, char* error)
{
    if (ptr == NULL) {
        printf("%s\n", error);
        clearMemoryError();
    }
}

void checkDoublePointer(char** ptr, char* error)
{
    if (ptr == NULL) {
        printf("%s\n", error);
        clearMemoryError();
    }
}

char* readline()
{
    char* tm = NULL;
    char c;
    int size = 1;
    crln = malloc((size) * sizeof(char));
    while ((c = getchar()) != STOP) {
        if (c == EOF) {
            free(crln);
            return NULL;
        }
        crln[size - 1] = c;
        size++;
        tm = realloc(crln, (size) * sizeof(char));
        checkSinglePointer(tm, "E");
        crln = tm;
    }
    size++;
    tm = realloc(crln, (size) * sizeof(char));
    checkSinglePointer(tm, "E");
    crln = tm;
    crln[size - 1] = '\n';
    return crln;
}

int main(int argc, char* argv[])
{
    char** tm = NULL;
    text = malloc(text_size * sizeof(char*));
    checkDoublePointer(text, "E");
    while (shouldRead) {
        newline = readline();
        if (newline == NULL) {
            break;
        }
        text[text_size - 1] = newline;
        printf("%p", newline);
        printf("%s", text[0]);
        text_size++;
        tm = realloc(text, text_size * sizeof(char*));
        checkDoublePointer(tm, "E");
        text = tm;
    }
    clearMemory();
    return 0;
}

嗨,我正试图写一个程序,作为输入文本,然后扭转它。我正在检查内存泄漏使用valgrind,一切都很好,但当我试图e.x

printf("%s", text[0]); // Any other index also doesn't work.

我得到错误,,条件跳转或移动取决于未初始化的值(s)”,即使它包含打印的文本。

cetgtptt

cetgtptt1#

打印字符串时,printf需要字符串终止符'\0'。然而,找不到它会导致Valgrind错误,因为你很容易就能跳出你的错误字符串。解决这个问题的方法是使用calloc,如下所示:

char *str = calloc(sizeof(char), STRING_SIZE + 1);

这相当于这样做:

char *str = malloc(sizeof(char) * STRING_SIZE + 1);
str = memset(str, 0, STRING_SIZE + 1);

你的整个字符串将被字符串结束符填充,我建议在分配任何东西时总是这样做,以避免意外的行为。
另外,不要忘记检查malloccalloc是否返回NULL:这是很好的练习

相关问题