Let's go throug your post, shall we?
1) You didn't use code tags, which means you didn't read the forum announcements. That's bad.
Originally Posted by
goresus
HI guys,
In the following code, I am trying to allocate some memory for a character array of size 30.
2) Ok, so you just want 30 characters allocated. That's easy enough.
Originally Posted by
goresus
PLease let me know what I am doing wrong. Because here, even after freeing the memory I still see the first element there same as before freeing the memory.
3) That's very wrong, if you are in fact doing what you say you're doing. Never, ever try to access memory you've just freed.
4) /* after adding code tags... */
Code:
#include <stdio.h>
#include <stdlib.h>
char String[30];
There. You've just allocated 30 characters. Nothing more need be done. This is not dynamic memory allocation here. This is simply creating an array. You do not free this. Ever.
5) Here you make a pointer point at the array you have. You still don't ever call free on this the way you have it:
Code:
char *pString = String;
6) Here you go and change what pString points to. If you uncomment that line, you'll have another problem, which is that you haven't put anything in the array before you try to start printing bits and pieces of it. That's wrong to do.
Code:
//name of the array is synomus to the first element address?
int main(){
// printf(" %c\n",pString[0]);
pString = (char *)calloc(30, sizeof(char));
pString no longer points at your array. It's pointing at memory you've just allocated with calloc. Now it's safe to use free on the pointer pString.
7) Here you stick the letter 'a' in your array, not in the memory you've just allocated.
Code:
String[0] = 'a';
printf(" %c\n",String[0]);
free(pString);
printf(" %c\n",String[0]);
}
You don't ever put anything in the memor you've allocated. You simply allocate some, then free it, ignoring it entirely while you play games with your array.
Quzah.