Reputation: 13
I and dynamic memories are not friends. I always get a problem with them. And the task is simple to understand.
Task: Write a function readText that reads an arbitrary text (finalized by return) from the user and returns it as a string. In this first version of the function assume that the text can't be longer than a certain length (e.g.1000 characters). After the text has been read, the memory should be shortened to the minimal needed length.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXC 5
char *readText(int*lengh);
int main()
{
char *str= malloc(MAXC*sizeof(char));
if(str == NULL) {
printf("Kein virtueller RAM mehr verfügbar ...\n");
return EXIT_FAILURE;
}
int length=0;
str=readText(&length);
printf("Text: %s %d %c\n",str,length,*str);
str= realloc(str,length+1);
if(str == NULL) {
printf("Kein virtueller RAM mehr verfügbar ...\n");
return EXIT_FAILURE;
}
printf("Text: %s\n",str);
free(str);
printf("free\n");
return 0;
}
char *readText(int*lengh){
char *result1;
char result[MAXC];
printf("Read Text: ");
scanf("%s",&result);
result1=result;
*lengh=strlen(result);
return result1;
}
Results (the string thing just happened in a moment ago, and before I only had a problem with the realloc):
Read Text: hoi
Text: h╠ ` 3 h
Kein virtueller RAM mehr verf³gbar ... (No virtual RAM available)
Process returned 1 (0x1)
My worry is that my program is ok, but my RAM is not. So if this is the case or in general, please tell me how to fix RAM problems too. Would be amazing Thanks for looking at this and help me to improve.
Upvotes: 1
Views: 64
Reputation: 212198
The function readText
returns the address of a local variable. You cannot realloc
memory that was not obtained by malloc
(or calloc
, or strdup
, etc.), and the local variable from the function readText
was certainly not obtained from malloc
. So realloc
fails.
Upvotes: 2