simple char array, please help

Started by
15 comments, last by rip-off 10 years, 9 months ago

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;
}
Advertisement
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.

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;
}


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.

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;
}
[size=2][ 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 ]

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.

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;
}

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.

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;
}

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.

This topic is closed to new replies.

Advertisement