Newbie: strcpy() mangles first character of string

Warning: I'm very much a novice at C...

So, when I call this function:

char* procCallsign (char* csign, int ssid, boolean isLast){
     char* addrField;
     char* textssid;

     strcpy(addrField,"W9WI");
     return addrField;
}

it returns L9WI -- where the "L" isn't really an L but an ASCII 0xC0. (looks like a superscript L in the Windows Terminal font)

If I change

strcpy(addrField,"W9WI");

to

addrField="W9WI"

it returns W9WI as it should.

Since I suppose it matters, the variable into which the return value is being placed in the main loop() is declared:

char* dcsign = "TLMTST";

I've played with C before & never did understand string handling....

The addrField variable is declared as a pointer. But, what does it point to? It is not initialized. Then, you copy some characters to wherever it is it points to (some random location in memory), and return that random address.

It's not surprising that you get garbage back.

In procCallsign, you need to allocate some space, and point addrField at that space, before copying chars to that space.

Ah. That makes an enormous amount of sense. As you may have guessed, my programming experience is in Perl where you can initialize things on the fly... and it's VERY difficult to get in the habit of initting everything first.

Change it to char* addrField="NOCALL\0"; and it works fine. Thanks!

Doug,

A couple of notes:

You don't need the \0 at the end of the string. When you put in a string constant with double quotes, the compiler automatically puts one of those at the end of the string.

Second, and more importantly, your function is returning a pointer that points to a string constant defined inside your function. While it may always work, I don't think it's guaranteed to do so.

The other way to do it is to declare a static character array inside your function. Make sure it's big enough to hold the biggest string you'll be using:

#define MAXSTR 10    // or whatever it needs to be
char* procCallsign (char* csign, int ssid, boolean isLast){
     static char addrField[MAXSTR+1];
     char* textssid;

     strcpy(addrField,"W9WI");
     return addrField;
}

By making 'addrField' static, it will stay around in memory after the function returns. Non-static variables (a/k/a automatic variables) are on the stack and are popped off the stack when a function returns.

Regards,

-Mike

I'm sure we are only seeing a portion of the code. If all you are trying to do is make a dynamic copy of an array, strdup will allocate the space and copy the character data to it. When the function returns, the pointed to memory is still allocated and pointed to, so it is safe to use it.