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

问题描述 投票:0回答:1
//#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.

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

c memory valgrind
1个回答
0
投票

打印字符串时,

printf
需要一个字符串终止符 ' '。但是,找不到它会导致 Valgrind 错误,因为您很容易超出 malloc-ed 字符串。解决这个问题的方法是使用
calloc
,像这样:

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

相当于这样做:

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

您的整个字符串将充满字符串终止符,我建议在分配任何内容时始终这样做,以避免意外行为。

此外,不要忘记检查

malloc
calloc
是否返回
NULL
:这是很好的做法。

© www.soinside.com 2019 - 2024. All rights reserved.