473,396 Members | 2,018 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

trying to understand C string pointers

Hi, I'm new with pointers actually. And im struggling to understand a function im trying to write....what im trying to understand is when a caller passes in a string pointer to a function that tries to clear up the pointer, why doesn't it get cleared up when we return to the caller? Here is an example :


Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h> 
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. void cfun(void);
  6. void cfun2(char *name2);
  7. int main ()
  8. {
  9.     cfun();
  10.  
  11.     return 0;
  12. }
  13.  
  14. void cfun(void)
  15. {
  16. char *name;
  17. name = (char *)malloc(20*sizeof(char));
  18.  
  19.     name = "wwoohoho";
  20.  
  21.     cfun2(name);
  22.  
  23.     printf("back to cfun's name at the end ..%s\n",name);
  24.  
  25.  
  26. }
  27.  
  28. void cfun2(char *name2)
  29. {
  30.     printf("in...%s\n",name2);
  31.  
  32.     free(name2);
  33.     name2 = NULL;
  34.  
  35.     printf("cfun2 after freeing name...%s\n",name2);
  36. }
  37.  
result :

in...wwoohoho
cfun2 after freeing name...(null)
back to cfun's name at the end ..wwoohoho

I was reading around, that arrays pass by reference to a function in C. So how come after I clear up the array in cfun2, I still get to see the string after exiting cfun2 and back to cfun?
May 15 '10 #1
5 1963
donbock
2,426 Expert 2GB
cfun allocates 20 bytes of heap storage and stores the pointer to that allocation in pointer variable name. Normally I would warn you to test the malloc return value to make sure it was successful, but in this case it doesn't matter. The next thing it does is throw away that value when it overwrites name with the pointer to a string constant that holds "wwoohoho".

You should have gotten a runtime error when cfun2 called free. The pointer passed to free is the string constant, not the memory allocated by malloc in cfun. Furthermore, the final printf in cfun2 should also have provoked a runtime error when it dereferenced pointer name2 after it was set to NULL.

Probably you meant to do the following instead of the assignment in cfun.
Expand|Select|Wrap|Line Numbers
  1. strcpy(name, "wwoohoho");
May 17 '10 #2
donbock, im not sure why im not getting any runtime error, im actually using pellesC for windows to try it out. I'm not too familiar with C, please bare with me..

The purpose of this scenario is because I wanted to find out what happens if a caller calls a function that tries to free up the pointer it passes in to. In this case, cfun2 tries to free up cfun's allocated heap.

I also wanted to know if the the 'name' in cfun and 'name2' in cfun2 is actually pointing to the same address..because im assuming 'name' was passed by reference into cfun2 and thus they're not local variables inside their own function.

By right, printf("back to cfun's name at the end ..%s\n",name); should just produce an error since it was freed inside cfun2
May 17 '10 #3
It's been a long time since I coded in C. I'm mostly in C++ now, so please take this comment with a grain of salt.

I think that C passes by value, so name2 = NULL may only be setting parameter to NULL, not the original name argument.

If that's the case, then name is still pointing to the same block of memory, whether it's free or not. You might be able to confirm this by printing the address of name (&name, I think), both before and after the call to cfun2.

If my hunch is correct, then name has become a dangling reference. The reason you're still seeing it print out wwoohoho is because it is still pointing to the same memory as before. While this memory has been freed, it has not been allocated to anything else.

You're lucky... well actually you're unlucky, because this is a land mine waiting to blow up.

Eventually, that memory will be reallocated to something else. Then when the printf occurs, it could core dump. The real headache is that you don't know where it may or may not core dump. It could be in your code, or your code could change that memory and the other program using it will core dump, and that poor developer will be left scratching his head wondering why his code core dumped when everything looked fine.

Because of this I STRONGLY suggest that you alwasy allocate and free memory in the same relative stack depth where possible, and even in the same method where possible. This isn't always possible, but when one method allocates memory and another one frees it, you run a much greater risk of having a memory issue.

NOTE: You could run into similar issues by declare a pointer, but not allocating any space for it. If the point just happens to be pointing to memory that "works" for your application, it will appear to work. If it's pointing to something else, it won't work and it won't work badly. Unfortunately, "working" vs "not working" is somewhat random. Not working is much better, because you have a better chance to find your problem and correct it.
May 17 '10 #4
donbock
2,426 Expert 2GB
Expand|Select|Wrap|Line Numbers
  1. int main () { 
  2.     cfun(); 
  3.     return 0; 
  4.  
  5. void cfun(void) { 
  6.     char *name; 
  7.     name = (char *)malloc(20*sizeof(char)); 
  8.     name = "wwoohoho"; 
  9.     cfun2(name); 
  10.     printf("back to cfun's name at the end ..%s\n",name); 
  11.  
  12. void cfun2(char *name2) { 
  13.     printf("in...%s\n",name2); 
  14.     free(name2); 
  15.     name2 = NULL; 
  16.     printf("cfun2 after freeing name...%s\n",name2); 
  17. }
  • The assignment causes line 9 to lose track of the memory allocated by line 8. This is a classic memory leak.
  • Line 16 tries to free the constant string "wwoohoho". What happens when you try to free memory that hasn't been allocated is undefined. Some systems would give you a runtime error.
  • Line 18 dereferences the NULL pointer. This pointer doesn't point anywhere. What happens is undefined. Some systems would give you a runtime error.
  • Line 11 -- notice that name still points at the string constant so of course this line still prints out "wwoohoho".
May 17 '10 #5
It passes by value? does this mean freeing the pointer memory on cfun2 and cfun are totally independent of each other?


i'm trying to find out whether this is the case because im worried that if a pointer to a string was passed into a function but was freed by its called function and someone tries to use the pointer after the called function...is that gonna be a problem? If it's by value..i don't think so, if it's by reference..then yes.
May 21 '10 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Paul | last post by:
Hi, I'm new to c and I have no idea what I'm doing wrong. Running the attached program gives me the output: t1: 1234567890123456STRANGE t2: STRANGE But only when the first string is 16 or...
2
by: Paul Diaconescu | last post by:
Hi, I'm new to c and I don't have any clue to what I'm doing wrong. This program gives me the output: t1: 1234567890123456STRANGE t2: STRANGE ^ (this is strange) But only when the...
8
by: junky_fellow | last post by:
what would be the output for the following piece of code ? if ( "hello" == "hello" ) printf("True\n"); else printf("False\n"); What is the reason for that ?
2
by: Bob Dankert | last post by:
I need to use functions through PInvoke which accept and return pointers to strings. What is the best way to get string pointers (IntPtr I am guessing?) to pass into these functions, and the best...
32
by: santosh | last post by:
In following code char str = "asdf" ; str = 's' ; is possible. But char *str = "asdf" ; str = 's' ; is an run-time error. What i understand is *str = "asdf" is stored in Read-only-Memory....
4
by: VJALZME | last post by:
Hi to all, I am having a doubt that, it is possible to assign a address of string varaibles address to string pointer.is it possible,then how can we do ? Thanks and regards, Vjee.
2
by: VJALZME | last post by:
Hi, Is it possible to assign string variables address to a string pointers ? say that, char a; char *sptr; ...
2
by: ashwini1680 | last post by:
Hi there, I am very confused with how string pointers are interpreted in memory? how we get the strings using subscript notation because as with pointers if we denote array name with subscript ,we...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.