Jump to content

  • Log In with Google      Sign In   
  • Create Account


simple char array, please help


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
16 replies to this topic

#1 musafir2007   Members   -  Reputation: 188

Like
1Likes
Like

Posted 26 June 2013 - 02:13 PM

Hi, I am trying to simple return a string but I get this error:

In function 'getNetworkAtPriority':

warning: function returns address of local variable
In function 'main':
error: incompatible types in assignment

 

Please help what I am doing wrong? thanks

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char * getNetworkAtPriority( )
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}

int main()
{
    char entry1[14];
    entry1 = getNetworkAtPriority( "1" );

    return 0;
}

Edited by musafir2007, 26 June 2013 - 02:19 PM.


Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9575

Like
2Likes
Like

Posted 26 June 2013 - 02:27 PM

For the first warning, when you try to return an array, what you're actually doing is returning a pointer to the first element of the array. In your code, you allocate the array as a local variable meaning that it gets destroyed when you leave the function. This means that the pointer you return is pointing to garbage. If you're using C++ you can use the std::string class instead of a char * as a return type. If you're using plain C then you have the choice of either passing the address of a buffer that the function will fill with the string data or dynamically allocating the buffer to be returned. For instance you can allocate a buffer with malloc() before the sprintf() call or use strdup() on the buffer after the sprintf() call to return a duplicate of the string.

For the error, you are trying to use assignment on a pointer to an array. This isn't legal C or C++. In C++ if you use std::string instead of a char array for entry1 you can use assignment. In C you can use strcpy() or a similar copy function to copy the contents of the returned string to your buffer.

#3 Vortez   Crossbones+   -  Reputation: 2698

Like
3Likes
Like

Posted 26 June 2013 - 04:30 PM

As SiCrane stated, your buffer will get invalid (out of scope) once the function return. It might work, and it might not... Use something like this instead:

void getNetworkAtPriority(char *firstArgument, char *pBuf)
{
    sprintf(pBuf, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    ZeroMemory(&entry1[0], 14);

    getNetworkAtPriority("1", &entry1[0]);

    return 0;
}



Edited by Vortez, 26 June 2013 - 04:33 PM.


#4 Khatharr   Crossbones+   -  Reputation: 2974

Like
2Likes
Like

Posted 26 June 2013 - 07:45 PM

As SiCrane stated, your buffer will get invalid (out of scope) once the function return. It might work, and it might not... Use something like this instead:

void getNetworkAtPriority(char *firstArgument, char *pBuf)
{
    sprintf(pBuf, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    ZeroMemory(&entry1[0], 14);

    getNetworkAtPriority("1", &entry1[0]);

    return 0;
}


 
Guard that against buffer overrun!
 
When you supply a buffer pointer to a function you should always provide the length of the buffer as well, and ensure that the function does not write beyond the end of the buffer.
 
int stuffToBuff(char* buffer, size_t bufferLength) {
  char thingToCopy[] = "Hello, world!";
  if(strlen(thingToCopy) >= bufferLength) {
    return -1; //indicate failure
  }
  strcpy(buffer, thingToCopy);
  return 0; //indicate success
}

int main() {
  char buf[20];
  int result = stuffToBuff(buf, 20);
  if(result == -1) {
    //there was an error!
  }
  return 0;
}
Remember that C-style strings require a zero at the end, so your buffer needs to be one longer than the number of characters being copied.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#5 Cornstalks   Crossbones+   -  Reputation: 6974

Like
2Likes
Like

Posted 26 June 2013 - 08:00 PM

Guard that against buffer overrun!
 [...]

Or even simpler:
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);

    return 0;
}

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#6 rip-off   Moderators   -  Reputation: 8165

Like
2Likes
Like

Posted 27 June 2013 - 03:55 AM

Note that you can return a literal string from a function safely, a string literal lives for the entire duration of the program. However, you cannot modify the literal, so the return value should be marked "const", as would the variable which would receive this result.

 
const char *getNetworkAtPriority()
{
    return  "mcc-mnc-umts";
}

The only risk here is the function signature would have to change if you wanted to change the implementation to be more dynamic later.



#7 musafir2007   Members   -  Reputation: 188

Like
0Likes
Like

Posted 27 June 2013 - 11:11 AM

Thanks all!

what if I want to try this with global variable?

 

why [mod edit: are these] not working?

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
char* getNetworkAtPriority()
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}
 
int main()
{
    entry1 = getNetworkAtPriority( "1" );
    return 0;
}

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
char* getNetworkAtPriority()
{
    char returnValue[14];
    sprintf( returnValue, "mcc-mnc-umts");
    return returnValue;
}
 
int main()
{
    strcpy(entry1, getNetworkAtPriority());
    printf("Return:%s", entry1);
    return 0;
}

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char entry1[14];
 
void getNetworkAtPriority()
{
    sprintf( entry1, "mcc-mnc-umts");
    //return returnValue;
}
 
int main()
{
    //strcpy(entry1, getNetworkAtPriority());
    printf("Value:%s", entry1);
    return 0;
}

Edited by rip-off, 27 June 2013 - 05:12 PM.
mod edit: restoring defaced question


#8 Brother Bob   Moderators   -  Reputation: 8090

Like
1Likes
Like

Posted 27 June 2013 - 11:22 AM

As SiCrane said in the very first reply; you are returning a local array. As soon as the function getNetworkAtPriority returns, the array no longer exists. It doesn't matter that some other array is global or not, the array returnValue is destroyed and no longer exists at the time you try to use strcpy on it.



#9 musafir2007   Members   -  Reputation: 188

Like
0Likes
Like

Posted 27 June 2013 - 12:16 PM

I really like the following way of doing it, and it seems to work on new compiler,
But my c compiler doesn't seem to support snprintf. What alternative do i have?
Thanks!
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}
 
int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);
    printf("Return:%s", entry1);
    return 0;
}

Edited by musafir2007, 27 June 2013 - 12:17 PM.


#10 Serapth   Crossbones+   -  Reputation: 5371

Like
0Likes
Like

Posted 27 June 2013 - 12:50 PM

I really like the following way of doing it, and it seems to work on new compiler,
But my c compiler doesn't seem to support snprintf. What alternative do i have?
Thanks!
 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void getNetworkAtPriority(char* buffer, size_t bufferLength)
{
    snprintf(buffer, bufferLength, "mcc-mnc-umts");
}
 
int main()
{
    char entry1[14];
    getNetworkAtPriority(entry1, 14);
    printf("Return:%s", entry1);
    return 0;
}

Just use memcpy.

You should try to avoid the printf functions if you don't need the advanced formatting they provide.

True story, I once worked a at a bank, contracted to re-architect the code for the teller systems for an eventual port to Java ( which coincidentally never happened... Over a decade later, that same C++ code is running strong... ). Anyway in the process of modularizing a ton of code I happened to get into a low level logging function. Basically every single transaction was logged to the file system, so if there was fraud, a crash, whatever, they could play back each individual tellers transactions at the application level. Anyways there was a call to fprintf that always copied the same sized buffer ( a time stamp ) to a fixed sized string, I swapped out to use a straight memory copy instead...


Net effect? The entire application nearly doubled in speed. We were actually getting thank you emails from the branches over making such big improvements to the application,


Sorry, old many memory moment is now complete.

#11 SiCrane   Moderators   -  Reputation: 9575

Like
0Likes
Like

Posted 27 June 2013 - 01:43 PM

Which compiler are you using? It may have snprintf(), but with a different spelling. Ex: MSVC calls it _snprintf().



#12 Cornstalks   Crossbones+   -  Reputation: 6974

Like
0Likes
Like

Posted 27 June 2013 - 02:00 PM

But my c compiler doesn't seem to support snprintf. What alternative do i have?

If you're using GCC/Clang, you can turn on C99 mode (default is C89, I believe). snprintf is part of the C99 standard, not the C89 standard. To turn on C99 mode with GCC or Clang, just pass the -std=c99 flag to the compiler when compiling. Or change your IDE to use C99 mode if you're using an IDE.

 

If you're using MSVC... it's a bit tricker, see below.
 
 

Just use memcpy.


You should try to avoid the printf functions if you don't need the advanced formatting they provide.

 a) Unless you have good reason to, don't worry about premature optimization. b) memcpy isn't necessarily a good replacement. I specifically used snprintf because it always null terminates the string. Always. memcpy does not, nor does strncpy. Yes, he can use memcpy, but he would have to 1) determine how long the source buffer is, 2) determine how long the dest buffer is, 3) pick the min of the two, 4) ensure the copied string is null terminated. It's certainly possible to use memcpy, but judging by his skill level, I think it's more worthwhile to suggest things that are less likely to lead him to screwing up (or at the very least, pointing out the caveats of alternative methods).
 

Which compiler are you using? It may have snprintf(), but with a different spelling. Ex: MSVC calls it _snprintf().

It should also be pointed out that there are a few gotchas if you use MSVC's _snprintf. Most notably, _snprintf does not necessarily null terminate the string (like snprintf always does). Additionally, the return values are different.  Before anyone uses _snprintf, they should first read this.


Edited by Cornstalks, 27 June 2013 - 02:01 PM.

[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#13 Vortez   Crossbones+   -  Reputation: 2698

Like
0Likes
Like

Posted 27 June 2013 - 02:40 PM

 

As SiCrane stated, your buffer will get invalid (out of scope) once the function return. It might work, and it might not... Use something like this instead:

void getNetworkAtPriority(char *firstArgument, char *pBuf)
{
    sprintf(pBuf, "mcc-mnc-umts");
}

int main()
{
    char entry1[14];
    ZeroMemory(&entry1[0], 14);

    getNetworkAtPriority("1", &entry1[0]);

    return 0;
}


 
Guard that against buffer overrun!
 
When you supply a buffer pointer to a function you should always provide the length of the buffer as well, and ensure that the function does not write beyond the end of the buffer.
 
int stuffToBuff(char* buffer, size_t bufferLength) {
  char thingToCopy[] = "Hello, world!";
  if(strlen(thingToCopy) >= bufferLength) {
    return -1; //indicate failure
  }
  strcpy(buffer, thingToCopy);
  return 0; //indicate success
}

int main() {
  char buf[20];
  int result = stuffToBuff(buf, 20);
  if(result == -1) {
    //there was an error!
  }
  return 0;
}
Remember that C-style strings require a zero at the end, so your buffer needs to be one longer than the number of characters being copied.

 

 

Yea, i though about that, but i didn't add it because i though it would obscure the important parts...

 

btw, shouldn't

 

if(strlen(thingToCopy) >= bufferLength) {

 

be

 

if(strlen(thingToCopy) <= bufferLength) {

 

???

 

I think you made a typo...


Edited by Vortez, 27 June 2013 - 02:52 PM.


#14 Cornstalks   Crossbones+   -  Reputation: 6974

Like
0Likes
Like

Posted 27 June 2013 - 02:44 PM

btw, shouldn't

 

if(strlen(thingToCopy) >= bufferLength) {

 

be

 

if(strlen(thingToCopy) <= bufferLength) {

 

???

 

I think you made a typo...

No, (strlen(thingToCopy) >= bufferLength) is correct. It's checking if the length of the string that needs to be copied is longer than the buffer, and if so, returns an error. You can read it as "If the string is longer than the buffer, return -1 to indicate failure."


[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#15 Paradigm Shifter   Crossbones+   -  Reputation: 5266

Like
0Likes
Like

Posted 27 June 2013 - 02:47 PM

Cornstalks is correct.

 

I'd return the number of bytes copied rather than 0 from the function though to indicate success. It will be useful if you are appending strings (don't need to call strlen again).


"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#16 Vortez   Crossbones+   -  Reputation: 2698

Like
0Likes
Like

Posted 27 June 2013 - 02:48 PM

Oh lol, my bad, i didn't read the code carefully, im used to do the opposite (check if the string lenght is smaller than buffer size, then return -1 if not, or whatever)


Edited by Vortez, 27 June 2013 - 02:53 PM.


#17 rip-off   Moderators   -  Reputation: 8165

Like
0Likes
Like

Posted 27 June 2013 - 05:13 PM

@musafir2007, do not remove or replace questions, it makes the thread very confusing to follow. You can follow up in a separate reply. If you're making more than a minor edit, it is courtesy to indicate the nature of the edit, or as Vortez did, to use strike through to indicate the old post. But this behaviour is  generally more suitable for replies, where you might otherwise be leaving misleading information, than questions.

 

I have restored a hybrid post from the various questions you appear to have asked.


Edited by rip-off, 27 June 2013 - 05:14 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS