Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

am i completely wrong about pointers? 1

Status
Not open for further replies.

goresus

Programmer
Jan 15, 2005
3
US
HI guys,
In the following code, I am trying to allocate some memory for a character array of size 30. 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.

#include <stdio.h>
#include <stdlib.h>
char String[30];
char *pString = String;

//name of the array is synomus to the first element address?
int main(){
// printf(" %c\n",pString[0]);
pString = (char *)calloc(30, sizeof(char));
String[0] = 'a';

printf(" %c\n",String[0]);


free(pString);
printf(" %c\n",String[0]);
}
 
Don't use a pointer after free call. The address is freed logically. It's contents may be the same (or may not), this storage may belong to your program address space (or may not, and you may catch memory access exception).

But in your case you have access to automatic array String (automatically allocated in your program stack). You don't use dinamically allocated memory (referenced by pSrting after calloc) at all. You get it, you put it - that's all. Your String array and a memory referenced by pString (after calloc) are different things...

What's a problem?..
 
#include <stdio.h>
#include <stdlib.h>
char String[30];
char *pString = String;

int main(){
// printf(" %c\n",pString[0]);
pString = (char *)calloc(30, sizeof(char));


***** you just overlayed the pointer, and it no longer is pointing to the String, it is pointing to a new location in memory.
say String is at location 0x00ff. pString get set to 0x00ff when initialized. But your memory allocation sets pString to a new location 0xffdd, so it is no longer pointing to String. The best way is to use a debugger and actually see what is happening.

String[0] = 'a';

printf(" %c\n",String[0]);
printf(" %c\n",*(pString+0));
********** will give you a NULL as you used calloc and pString is an array of 30 nulls.

free(pString);
printf(" %c\n",String[0]);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top