Remove the space from infront of my C String - c

I have some code that outputs like this:
void exec_prompt(char * usr_name, char * host_name)
{
printf(" %s::%s\n", usr_name, host_name);
return;
}
But the print out doesnt look as expected:
geisst::ALPHA-DT2
There is that space at the front of the string.
The usr_name variable is passed from the main function and is returned from the getenv() function. The host_name variable is passed from the main function with the use of the following function:
char * returnHost()
{
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
return hostname;
}
Maybe the getenv() function adds a space?
Any help or advice is appreciated and please be nice :P
GeissT

The reason is that your format has a space: " %s::%s\n"
Just change it to:
printf("%s::%s\n", usr_name, host_name);

Related

Segmentation fault in c (C90), Whats the problem?

Heres my main.c:
int main() {
char *x = "add r3,r5";
char *t;
char **end;
t = getFirstTok(x,end);
printf("%s",t);
}
And the function getFirstTok:
/* getFirstTok function returns a pointer to the start of the first token. */
/* Also makes *endOfTok (if it's not NULL) to point at the last char after the token. */
char *getFirstTok(char *str, char **endOfTok)
{
char *tokStart = str;
char *tokEnd = NULL;
/* Trim the start */
trimLeftStr(&tokStart);
/* Find the end of the first word */
tokEnd = tokStart;
while (*tokEnd != '\0' && !isspace(*tokEnd))
{
tokEnd++;
}
/* Add \0 at the end if needed */
if (*tokEnd != '\0')
{
*tokEnd = '\0';
tokEnd++;
}
/* Make *endOfTok (if it's not NULL) to point at the last char after the token */
if (endOfTok)
{
*endOfTok = tokEnd;
}
return tokStart;
}
Why do i get segmentation fault running this main program?
I'm programming a two pass aseembler and i need a function that get parse a string by a delimiter, In this case a white space. Is it better to use strtok instead for this purpose?
I need a command pasrer - So that it will extract "add", an operand parser (By , delimiter), To extract "r3" and "r5". I wanted to check if this getFirstTok function is good for this purpose but when i try to run it i get a segmentation fault:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Thank you.
As pointed out in the comments, string literals are read-only, as they are baked into the compiled program. If you don't want to go with the suggested solution of making your "source program" a stack-allocated array of characters (char x[] = "add r3,r5"), you can use a function like strdup(3) to make a readable/writable copy like so:
#include <string.h>
[...]
char *rw_code = strdup(x);
t = getFirstTok(rw_code, end);
printf("%s", t);
free(rw_code); /* NOTE: invalidates _all_ references pointing at it! */
[...]
And as a little aside, I always make string literals constant const char *lit = "...", as the compiler will usually warn me if I attempt to write to them later on.

How to return a string from GetOpenFileNameA

This is a function to open a file dialog in Windows and return a string with the file name:
#include <windows.h>
#include <commdlg.h>
#include <string.h>
char* openFileDlg(char FileTypes[]);
char* openFileDlg(char FileTypes[]){
OPENFILENAME ofn;
char szFile[260];
HWND hwnd;
HANDLE hf;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = hwnd;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
strcpy(ofn.lpstrFilter,FileTypes);
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if(GetOpenFileNameA(&ofn)){
char *toReturn;
sprintf(toReturn,"%s",ofn.lpstrFile);
return toReturn;
}
else{
return NULL;
}
}
When I call this function and open a file, the process ends and returns value 3 (which means there is an error). How can I do so that this function returns a string with the path of the selected file?
Edit: I've changed my code to this and it still doesn't work:
#include <windows.h>
#include <commdlg.h>
#include <string.h>
void openFileDlg(char *toReturn[],char FileTypes[]);
void openFileDlg(char *toReturn[],char FileTypes[]){
OPENFILENAME ofn;
/*
Code for the settings of the GetOpenFileNameA, irrelevant in this question.
If you really need to know what's here, look at the code above.
*/
if(GetOpenFileNameA(&ofn)){
strcpy(*toReturn,ofn.lpstrFile);
}
else{
sprintf(*toReturn,"");
}
}
I should also say that if I press the Cancel button in the open file dialog box instead of selecting a file, it works fine. After some tests, I've noticed that it's the line strcpy(*toReturn,ofn.lpstrFile); that causes the error.
The pointer variable toReturn doesn't point anywhere, using it in any way without initializing it (i.e. making it point somewhere valid and big enough) will lead to undefined behavior
You have two solutions really:
Allocate memory dynamically and return a pointer to that. This of course requires the caller to free the memory when done with it.
Have the function take another two arguments: A pointer to a buffer and the length of the buffer. Then copy the string into that buffer, and return a boolean "true" or "false" success/failure status.
I recommend solution number two.
On an unrelated note, there's no need to use the expensive sprintf function in your case, a simple strcpy (or strncpy if you go with the second solution) will do.
You also have to remember in both cases that strings in C have an actual length of one more than e.g. strlen reports, for the terminating '\0' character.
In general, if you want to return a string in C, I'd use one of the following methods:
1) pass in a string buffer for the method to write to:
int openFileDlg(char FileTypes[], char* toReturn, int bufLen) {
/* ... */
snprintf(toReturn, bufLen, /* what you want to print */);
return ERROR; // status-code
}
/* ... */
char errorBuf[80];
int result;
result = openFileDlg(..., errorBuf, sizeof(errorBuf));
2) allocate memory, expect caller to free it:
char* openFileDlg(char FileTypes[]) {
/* ... */
char *toReturn = malloc(/* big enough */);
sprintf(toReturn, /* what you want to print */);
return toReturn;
}
/* ... */
char* error = openFileDlg(...);
if (error) {
/* ... */
free(error);
}
personally, I'd prefer (1) because it's safer. Option (2) is nicer to the API of the function, but has a risk of memory leaks if you forget to free the returned buffer. In a bigger project (especially with multiple people working on it) this is a very real risk.
(I realise this is pretty much the same as Joachim's answer, but his went up as I was writing mine)
You did not allocate memory for your return value. If you know the length of ofn.lpstrFile you could do this:
char *toReturn = malloc( (sizeOfLpstrFile + 1) * sizeof(char)) ;
sprintf(toReturn,"%s",ofn.lpstrFile);
return toReturn;
Still I consider this a bad idea because the calling function will have to free the memory which is not obvious from the interface.

How to add offset to a character pointer?

I have a the following declarations :-
char szsrcBuf[10000]; /* stores main bufer */
int iOff2Verify; /* offset to start of verify area*/
int iLen2Verify; /* length of data to verify */
Now when I call the function with the following parameters :-
/* process data to verify */
if ((iRet = Verify_Mid(&mach, (char *)(szsrcBuf + (int)iOff2Verify),
iLen2Verify)) != 0)
break;
The signature for the Verify_Mid() looks like :-
int CALLBACK Verify_Mid(bsapi_id *mach, char *inputData, int inputDataLen);
Things work great.
-------------------xxx above is the is my first way of coding, that works. xxx----------------------
However my code started getting big enough, where I need to re-structure the function of my original call. So I split out the part where I am calling Verify_Mid.... as such:-
iRet = Verify_Request(x, y, szsrcBuf, z, &iOff2Verify, iLen2Verify, (char *)abc, &iabcLen);
The signature for the new helper function Verify_Request is:-
int CALLBACK Verify_Request(unsigned char *x, int y, unsigned char *szsrcBuf, char *z,
int *iOff2Verify, int iLen2Verify, char *abc, int *iabcLen);
Now inside my Verfiy_Request () :-
do{
..... stuff....
/* process data to verify */
if ((iRet = Verify_Mid(&mach, (char *)(szsrcBuf + (int)iOff2Verify),
iLen2Verify)) != 0)
break;
.... stuff .....
}while(0);
Until this point everything looks ok (on the apparent), however when I go to my Verfiy_Mid (), there is an error reading the 2nd parameter (char * inputData)... I have tried a couple of things with how I am passing the 2nd parameter, but to no avail... can anyone help me understand how to add the offset and then correctly pass it as a parameter to my next function ?
You are passing iOff2Verify as a pointer to function Verify_Request(...);
Therefore in order to actually pass data stored in that pointer, your call to Verify_Mid(...) needs to reflect that as well.
do{
/* process data to verify */
if ((iRet = Verify_Mid(&mach, (char *)(szsrcBuf + (*iOff2Verify)),
iLen2Verify)) != 0)
break;
}while(0);
By the way, if you don't need to change value of iOff2Verify in Verify_Request, there is no need to pass it as a pointer, just regular int would suffice and it would save you all the trouble of pointer debugging, which is usually just pure hell

char * disappears if I don't print it?

I have a very odd problem here. I basically have a function which takes in a char* and it splits the string and returns the substring. My problem is if I print length of the char* THEN return it then the value remains but if I don't call the function to get the length then when it comes out of the function it disappears.
I've probably explained it poorly above so I'll copy and paste segments of the code below:
void processFile (char *currentLine, int currentLineNumber)
{
int type;
char *accountName, *secCodeRef, *secCode = NULL, *reference = NULL;
if ((type = getType(currentLine)) == TYPE_HEADER)
{
accountName = strtok (currentLine, " "); //Remove "Type"
accountName = strtok (NULL, " "); //Get Account Name
secCodeRef = strtok (NULL, " "); //get Security code and reference
secCode = getSecCode(secCodeRef, secCode); //Get Security Code
printf("TEST:%s\n", secCode);
}
Basically secCodeRef is a string that contains both the security code and the reference (.e.g.) GB0007980592REFERENCE1. The first 11 characters are the security code and the rest is the reference. So I pass this string into a function called getSecCode: (SECCODELENGTH is 13 btw)
char *getSecCode (char *secCodeRef, char *secCode)
{
char SecCode[SECCODELENGTH];
char *SecuCode = (char*)&SecCode;
memcpy(SecCode, &secCodeRef[START], SECCODELENGTH-1);
SecCode[SECCODELENGTH-1] = '\0';
printf("%d\n", getStringLength(SecuCode));
return SecuCode;
}
It extracts SecuCode ok when this line runs:
printf(%d\n, getStringLength(SecuCode));
The result is: (I'm reading from a file btw with different data in it)
12
TEST:GB0007980592
12
TEST:GB0007980593
12
TEST:GB0007980594
Which is correct
But when I comment out:
//printf(%d\n, getStringLength(SecuCode));
The output is:
TEST:
TEST:
TEST:
Why does the print statement affect the return value at all?
char SecCode[SECCODELENGTH];
char *SecuCode = (char*)&SecCode;
SecCode is a local array to function getSecCode() and you return the address of this local array which will lead to undefined behavior.

Strange characters from char array in structure

Here are my structures (defined in a header file):
typedef struct
{
char *name;
char *value;
} struct_param;
typedef struct
{
char *UID;
int number;
char *type;
char *name;
struct_param param[10];
} struct_cmd;
the prototype :
struct_cmd *ParseFile(char buffer[]);
The function in the c file:
struct_cmd *ParseFile(char buffer[])
{
struct_cmd *cmd;
cmd = malloc(sizeof(struct_cmd));
...
if (mxmlGetFirstChild(node_msgUID) != NULL)
cmd->UID = node_msgUID->child->value.opaque;
...
printf("Message Type :: %s | Message UID :: %s \n", cmd->type, cmd->UID);
...
return cmd;
}
The printf in ParseFile works perfectly.
Now, from the main function:
int main(int argc, char **argv)
{
...
struct_cmd *mystruct;
mystruct = malloc(sizeof(struct_cmd));
mystruct = ParseFile(buf);
printf("Message Type :: %s | Message UID :: %s \n", mystruct->type, mystruct->UID);
...
}
The same printf doesn't work. The function returns the structure, but values are weird... It's not values, but strange characters.
Any idea?
Thanks
You are making a shallow copy from the data allocated by Mini-XML to your own struct cmd.
For example, this statement copies a pointer, not the actual characters:
cmd->UID = node_msgUID->child->value.opaque;
cmd->UID still refers to the original memory block allocated by Mini-XML. There's nothing wrong with that, just remember that this memory will be de-allocated once you call mxmlDelete. Which is probably what you are doing somewhere near the end of function ParseFile. I am guessing here, since you did not post all your code.
Possible solutions:
Instead of a shallow copy, make a deep copy, e.g. with strdup: cmd->UID = strdup(node_msgUID->child->value.opaque);
Do all processing before freeing memory.
Remember, you are programming in plain C, without a garbage collector. Memory management is your responsibility.
Just to be sure... I must use malloc before setting the value to my structure in the ParseFile function, right?
So as I said in a comment, if I manually set cmd->type = "type" in the ParseFile function, it's correctly showed in the console (in the main).
But if I don't, strange characters are displayed.
I changed the declaration of my structure and added "extern", but it didn't change anything.
I'm lost...
define cmd globally instead of locally in the function:
struct_cmd *ParseFile(char buffer[])
{
struct_cmd *cmd;
cmd = malloc(sizeof(struct_cmd));
...
if (mxmlGetFirstChild(node_msgUID) != NULL)
cmd->UID = node_msgUID->child->value.opaque;
...
printf("Message Type :: %s | Message UID :: %s \n", cmd->type, cmd->UID);
...
return cmd;
}
to:
struct_cmd *cmd;
struct_cmd *ParseFile(char buffer[])
{
cmd = malloc(sizeof(struct_cmd));
...
if (mxmlGetFirstChild(node_msgUID) != NULL)
cmd->UID = node_msgUID->child->value.opaque;
...
printf("Message Type :: %s | Message UID :: %s \n", cmd->type, cmd->UID);
...
return cmd;
}

Resources