//#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;
}
Hi, I am trying to write a programm that as input takes text and then reverse it. I am checking for memory leaks using valgrind, everything is fine but when I am trying to e.x
printf("%s", text[0]); // Any other index also doesn't work.
I am getting error ,,Conditional jump or move depends on uninitialised value(s)" even though it contains text which is printed.
When printing a string, printf
will need a string-terminator '\0'. However, not finding it would cause a Valgrind error, since you are easily able to go out of your malloc-ed string. A fix to that would be to use calloc
, like so:
char *str = calloc(sizeof(char), STRING_SIZE + 1);
Which is equivalent to doing this:
char *str = malloc(sizeof(char) * STRING_SIZE + 1);
str = memset(str, 0, STRING_SIZE + 1);
Your whole string will be filled with string-terminator characters, which I would recommend to always do when allocating anything, to avoid unexpected behaviour.
Also, don't forget to check if malloc
or calloc
returns NULL
: it's good practice.