473,512 Members | 15,089 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning pointers to locally allocated memory

22 New Member
I know it's not "best practice" returning pointers to local variables, but in this case I think i need it.

I'm writing a method to remove some characters at the beginning and some at the end of a string and return the result as a pointer to memory allocated in the function.

I developed the function separately, it worked, but when implemented with the rest of the code it doesn't return anything... It seems that the letters is added to the var new, but when i try printing the string, nothing is returned....

Expand|Select|Wrap|Line Numbers
  1. char * prepareMessage(char str[]) {
  2.     int i=0, j=0, state=0;
  3.  
  4.     while(str[i]==' ') { i++; } //skip whitespace
  5.  
  6.     while(state == 0 && str[i]!='\0') { //find the start of the message (after 'new ')
  7.         if(str[i]=='n' && str[i+1]=='e' && str[i+2]=='w' && str[i+3]==' ') {
  8.             state = 1;
  9.             i += 4;
  10.         }
  11.         i++;
  12.     }
  13.  
  14.     char * new = malloc(strlen(str)-i);
  15.     while(str[i]!='\0') { //copy the chars to the new var
  16.         *(new+j) = str[i++];
  17.         j++;
  18.     }
  19.  
  20.     if(*(new+j-1)=='\"') { //remove trailing " and append \0
  21.         *(new+j-1) = '\0';
  22.     } else { //no trailing " - something wrong, free mem and return NULL
  23.         free(new);
  24.         return NULL;
  25.         debug("ERROR: NO TRAILING \"");
  26.     }
  27.  
  28.     return new;
  29. }
The str[] comes from

Expand|Select|Wrap|Line Numbers
  1. char inputBuffer[200] = "";
  2. fgets(inputBuffer, 200, stdin)
Hope someone is able to point me in the right direction...

Thanks in advance!
Oct 12 '08 #1
7 2020
JosAH
11,448 Recognized Expert MVP
Just a few remarks:

1) your first two while loops can be replaced by a single strstr() function call.
2) your third while loop can be replaced by a single strcpy() function call.
3) why do you use two notations? i.e. s[i] and *(s+i)

kind regards,

Jos
Oct 12 '08 #2
krreks
22 New Member
Just a few remarks:

1) your first two while loops can be replaced by a single strstr() function call.
2) your third while loop can be replaced by a single strcpy() function call.
3) why do you use two notations? i.e. s[i] and *(s+i)
Expand|Select|Wrap|Line Numbers
  1. char * prepareMessage(char str[]) {
  2.     int i=0;
  3.     char * new;
  4.  
  5.     char * pMsgStart = strstr(str, "new ");
  6.     if(pMsgStart!=NULL) {
  7.         int i = (strstr(str, "new ")-&str[0])+5;
  8.         new = malloc(strlen(str)-i);
  9.         strcpy(new, (str+i));
  10.         if(new[strlen(new)-1] == '"') {
  11.             new[strlen(new)-1] = '\0';
  12.             return new;
  13.         } else {
  14.             return NULL;
  15.         }
  16.     } else
  17.         return NULL;
  18. }
Then the code is more compact and uses the built in functions (smart :). But I'm still not getting proper output... I think it might be the input that's not proper :s

This is my testcase which makes it fail:

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char * prepareMessage(char str[]) {
  6.     int i=0, j=0, state=0;
  7.     char * new;
  8.  
  9.     char * pMsgStart = strstr(str, "new ");
  10.     if(pMsgStart!=NULL) {
  11.         int i = (strstr(str, "new ")-&str[0])+5;
  12.         new = malloc(strlen(str)-i);
  13.         strcpy(new, (str+i));
  14.         if(new[strlen(new)-1] == '"') {
  15.             new[strlen(new)-1] = '\0';
  16.             return new;
  17.         } else {
  18.             return NULL;
  19.         }
  20.     } else
  21.         return NULL;
  22. }
  23.  
  24. int main() {
  25.     char inputBuffer[200];
  26.  
  27.     do { 
  28.         if(fgets(inputBuffer, 200, stdin)==0) {
  29.             strcpy(inputBuffer,"exit");
  30.         } else {
  31.             char * new = prepareMessage(inputBuffer);
  32.             printf("%s\n",new);
  33.             free(new);
  34.         }
  35.     } while (strcmp ("Apple",inputBuffer) != 0);
  36.  
  37.  
  38.     return 0;
  39. }
K
Oct 12 '08 #3
JosAH
11,448 Recognized Expert MVP
You should malloc at least one byte more on line #12; the \0 character needs to
be stored as well.

kind regards,

Jos
Oct 12 '08 #4
JosAH
11,448 Recognized Expert MVP
ps. oh, and btw, the fgets() function also returns the end-of-line character(s) in
the buffer so the last character can never be a double quote in your buffer.

kind regards,

Jos
Oct 12 '08 #5
krreks
22 New Member
You should malloc at least one byte more on line #12; the \0 character needs to
be stored as well.
Ok. But it's not much use if nothing is returned... It's something with the fgets i think... If I use a plain array like this:

Expand|Select|Wrap|Line Numbers
  1. char inputBuffer[200] = "new \"message\"";
  2. char * new prepareMessage(inputBuffer);
  3.  
it works, but the value comes from fgets() like this:

Expand|Select|Wrap|Line Numbers
  1. char inputBuffer[200] = "";
  2.     char * tmp = malloc(200);
  3.  
  4.     do { 
  5.         if(fgets(tmp, 200, stdin)==0) {
  6.             strcpy(inputBuffer,"exit");
  7.         } else {
  8.             strcpy(inputBuffer, tmp);
  9.             char * new = prepareMessage(inputBuffer);
  10.             printf("%s\n",new);
  11.             free(new);
  12.         }
  13.     } while (strcmp ("Apple",inputBuffer) != 0);
it's not working... Why!?
Oct 12 '08 #6
krreks
22 New Member
it's not working... Why!?
I still don't know why, but this code seems to be working. Not 100% shure, but it gives me the right string every time :)

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char * prepareMessage(char str[]) {
  6.     int i=0, j=0, state=0;
  7.     char * new;
  8.  
  9.     char * pMsgStart = strstr(str, "new ");
  10.     if(pMsgStart!=NULL) {
  11.         int i = (strstr(str, "new ")-&str[0])+5;
  12.         new = malloc(strlen(str)-i+1);
  13.         strcpy(new, (str+i));
  14.         if(new[strlen(new)-2] == '"') {
  15.             new[strlen(new)-2] = '\0';
  16.             return new;
  17.         } else {
  18.             return NULL;
  19.         }
  20.     } else {
  21.         return NULL;
  22.     }
  23. }
  24.  
  25. int main() {
  26.     char inputBuffer[200] = "";
  27.     char * tmp = malloc(200);
  28.  
  29.     do { 
  30.         if(fgets(tmp, 200, stdin)==0) {
  31.             strcpy(inputBuffer,"exit");
  32.         } else {
  33.             strcpy(inputBuffer, tmp);
  34.             char * new = prepareMessage(inputBuffer);
  35.             printf("%s (%d chars long)\n",new, strlen(new));
  36.             free(new);
  37.         }
  38.     } while (strcmp ("Apple",inputBuffer) != 0);
  39.  
  40.     return 0;
  41. }
  42.  
  43.  
Oct 12 '08 #7
JosAH
11,448 Recognized Expert MVP
it's not working... Why!?
Read my reply #5.

kind regards,

Jos
Oct 12 '08 #8

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

Similar topics

2
2636
by: mosfets | last post by:
Hi, I'm having a little trouble figuring out the difference in terms of memory allocation between: class person_info; class A { private:
1
2312
by: Guha | last post by:
I have a problem with returning a 2D array using a function which is called in main(). The piece of the code is given below. This is a test code only. #include"stdio.h" #include"alloc.h" ...
8
1864
by: shan | last post by:
How to return an two dimensional array in user defined function to main function. I think it is posible by using pointers but don't know how to code.or is there any method without using...
7
2140
by: enki | last post by:
What I want to do is create sprites and put them in a vector. I know that this specific example dosn't realy fit in this group but my sprite are ponters. vector<*sprite>spvec; sprite *...
2
19309
by: Bhan | last post by:
Hi, Can I get answers for the following: 1. Usage of Double Pointers during allocation memory.Heard that if memory is to be allocated by someone who is working on another module,then we...
39
19559
by: Martin Jørgensen | last post by:
Hi, I'm relatively new with C-programming and even though I've read about pointers and arrays many times, it's a topic that is a little confusing to me - at least at this moment: ---- 1)...
59
5055
by: MotoK | last post by:
Hi Experts, I've just joined this group and want to know something: Is there something similar to smart pointers in C or something to prevent memory leakages in C programs. Regards MotoK
36
2235
by: MC felon | last post by:
how do we return strings or arrays from a function? i tried.. char some_func() //where i thought char would tell the compiler that the return is a string { char str; //something; return...
25
12989
by: J Caesar | last post by:
In C you can compare two pointers, p<q, as long as they come from the same array or the same malloc()ated block. Otherwise you can't. What I'd like to do is write a function int comparable(void...
0
7252
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
7153
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
7371
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7432
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
7517
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
3230
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1583
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
452
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.