Reputation: 1384
This program checks if given string is in alphabetical order and I am allocating new memory every time user enter a character but it is working fine if i don't allocate that memory Means (if i remove the commented line from the code below) is it a bug or some memory technique where is it getting memory from if i don't use that realloc()
line
#include<iostream>
#include<conio.h>
#include<stdlib.h>
bool Alphabetical(char DA[],unsigned short n)
{
for(n ;n>-1;n--)
if(n==0) return true;
else if((DA[n]<91&&DA[n-1]<91)&&(DA[n]<DA[n-1])) return false;
else if((DA[n]>96&&DA[n-1]>96)&&(DA[n]<DA[n-1])) return false;
else if((DA[n]<91&&DA[n-1]>96)&&(DA[n]+=32)&&(DA[n]<DA[n-1])) return false;
else if((DA[n]>96&&DA[n-1]<91)&&(DA[n]-=32)&&(DA[n]<DA[n-1])) return false;
return true;
}
int main()
{
int block=1,i=-1;
char *DA=(char*)malloc(1*block),c;
std::cout<<"Enter a string(ONLY ALPHEBATS,ANY LENGTH)\n";
while((c=getche())!=13)
if(c>64&&c<91||c>96&&c<123)
{
DA[++i]=c;
realloc(DA,1*(++block));/// i din't understand why is it working fine without this line
}
else std::cout<<"\b \b";
std::cout<<"\nreturned "<<Alphabetical(DA,i);
}
Upvotes: 0
Views: 121
Reputation: 847
You are allocating 1 byte with malloc
at the beginning of your program. malloc
can actually allocate more memory than what you request for various reasons (e.g., optimize future reallocations). Also, the operating system usually protects memory based on pages, so as long as you are accessing the same page, no error is raised.
Accessing memory that you have not explicitly allocated has an undefined behavior and must be avoided, even if your program seems to work.
As for your program, I guess that the error is that you are declaring c
as a char*
.
A pointer usually is 4 or 8 bytes long, while you are allocating just 1 byte. If you declare c
as char
, that has size 1 byte, your program should work.
Anyway, it is safer to use sizeof
when you allocate memory with malloc
or realloc
, because the size of a variable can vary on different systems. As an example on a 32-bit system a pointer is usually 4B, while is usually 8B on a 64-bit system.
Upvotes: 1