I am learning to use malloc & calloc.
I am using strlen with calloc to store the string in memory.
First thing is that I did not expect is that malloc is reserving 32 bytes for the string instead of strlen+1 bytes.
Secondly I am getting an exclamation point and some extraneous characters in memory that I have no idea how it got there. I thought it was just random characters so I used calloc instead of malloc but they still appear and always in the same position so it i do not think it is a random thing.
Appreciate any help to explain this.
Thanks
Here is the input
enter string
aasdfasdf
enter string
t43tq34
enter string
45t2q5tyqty
enter string
Here is the output x represents null character.
aasdfasdfxxxxxxxxxxxxxxx!xxxxxxx
t43tq34xxxxxxxxxxxxxxxxx!xxxxxxx
45t2q5tyqtyxxxxxxxxxxxxx�xxxxx
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define OFFSET 0x40
int readline(char *, int);
int main(int argc, char *argv[]) {
int count, index=0,i=0, stringDone=0;
char str[50]="", *chrptr, *initPtr=0;
do {
printf("enter string\n");
count=readline(str, sizeof(str));
//printf("%d\n", count);
if (count){ //allocate memory
chrptr=(char *)calloc(count,sizeof(char)); //returns pointer to, count includes null char
//printf("%p\n",chrptr);
if (chrptr == NULL){ //null term is already accounted for
printf("malloc error, exiting program\n");
exit (0);
}
if (index == 0) { //save pointer
initPtr=chrptr;
//printf("%p\n",chrptr);
}
//strcpy(chrptr,"test");
strcpy(chrptr,str); //strcpy copies the null char to chrptr
index++;
}
} while (count > 0);
chrptr=initPtr;
for(i = 0; i < (32*index) ; i++){
if (*chrptr != '\0'){
//stringDone=0;
printf("%c", *chrptr++);
}
else {
if (*chrptr++ == '\0') //&& stringDone==0) {
putchar('x');
//stringDone=1;
}
}
return 0;
}
int readline(char* mystr, int n){
char ch;
int i = 0;
while ((ch = getchar()) != '\n') {
if (i < n)
mystr[i++] = ch;
}
mystr[i]='\0'; //place null char at end of string
return i;
}