C: Returning String From Another Function - c

I'm new to C / pointers / memory management and am having trouble implementing a few functions for a project I'm working on.
In my builtins.c file, I have a function called printalias that is called to print all the alias names and corresponding values stored in my program. At the end, I want to print one of the alias names by retrieving it via another function called getal.
int x_printalias(int nargs, char *args[]) {
int i = 0;
// Loop through, print names and values
for(i = 0; i< 100; i++)
{
if(alias_names[i][0]!='\0' && !alias_disabled[i])
{
char * var = alias_names[i];
char * val = alias_vals[i];
fprintf(stderr,"%s = %s\n", var, val );
}
}
// This is where I want to retrieve the string from another function
char * hello = "brett";
hello = getal(hello);
fprintf(stderr,"Got alias for brett --> %s",hello);
return 0;
}
My getal function exists in my shellParser.c file and looks like this, generally performing the same looping and returning when it is found:
const char * getal(int nargs, char *args[])
{
fprintf(stderr,"\nRetrieving alias...\n");
int i = 0;
fprintf(stderr, "check1\n" );
fprintf(stderr,"Got args[0]: %s\n", args[0]);
while (alias_names[i][0]!='\0' && i < MAX_ALIAS_LENGTH ) // Find empty slot in variables array
{
fprintf(stderr, "check2\n" );
fprintf(stderr,"I is currently %i and current varible in slot is %s\n",i,alias_names[i]);
//strncpy(hello, variables[i], MAX_VAR_LENGTH); // Variable at current slot
if(strcmp(alias_names[i], args[0]) == 0) // If we have an entry, need to overwrite it
{
fprintf(stderr,"Found alias %s = %s at spot %i\n",args[0],alias_vals[i], i); // Not at end if here
return alias_vals[i];
}
i++;
}
fprintf(stderr, "check3\n" );
// Elided....
return '\0';
}
In the end of my printalias function, I want to test that this getal function is working by calling it on a hardcoded string "brett". However, when I call my printalias function from the command line, it makes it to the "Check 1" print statement and then simply quits without error or return value.
I think this has something to do with my memory management or incorrect declaration of variables with pointers. Can anybody spot something (or a lot of things) that I'm doing wrong here?

You must declarete list of argument for to call getal and it call with these
list.
And pointer of return values getal must be const char*
//....
// This is where I want to retrieve the string from another function
char * hello[] = {"brett"}; // this list argument for getal function
const char *strGetal;
strGetal = getal(1,hello);
fprintf(stderr,"Got alias for brett --> %s",strGetal);
return 0;
}

Example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** get_all(int argc, char **argv)
{
char *value;
char **values = NULL;
int i;
values = (char**) malloc(sizeof (char) * argc);
if (values == NULL) {
perror("malloc");
return NULL;
}
for (i = 0; i < argc; i++, argv++) {
value = strchr(*argv, ':');
values[i] = (value + 1);
}
return values;
}
int main()
{
char *args[] = {"key:a", "key:b", "key:c"};
char **values;
int i;
values = get_all(3, args);
for (i = 0; i < 3; i++) {
puts(values[i]);
}
return 0;
}

Related

trying to create an array of struct pointer but get heap/buffer/etc violation statistically

i have two structs
typedef enum { False = 0, True = 1 } bool;
//defenition of candy structure
typedef struct _Candy {
char candy_name[16];
bool vegan;
}Candy;
typedef struct _Child {
char child_name[16];
Candy *candy_of_child;
}Child;
now im trying to create an array of pointers that each one is Child type
[*Child,*Child...] etc
now i can initialize it i need to do it dynamically
the function that does in is:
int AllocateKidsArray(int NumOfKids, Child** ptr_to_child_arr) {
//=================================================
//"AllocateKidsArray" intializing an array of childrens
//Input: 1. int indicating the number of kids
// 2. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
// 2. pointer to an empty initialized array of childerns
//=================================================
// array of length NumOfKids, consisting of Child pointers
Child **ptr_to_childs = malloc(NumOfKids * sizeof(Child*));
int i;
for (i = 0; i < NumOfKids; i++) {
ptr_to_childs[i] = malloc(sizeof(Child));
strncpy((*ptr_to_childs[i]).child_name, "", 16);
(*ptr_to_childs)[i].candy_of_child = NULL;
}
*ptr_to_child_arr = *ptr_to_childs;
//for (i = 0; i < NumOfKids; i++) {
// free(ptr_to_childs[i]);
//}
//free(ptr_to_childs);
return 0;
}
im calling it from the main in the following manner:
int main(int argc, char** argv) {
//=================================================
if (argc < 3) {
printf("Incorrect number of arguments. Please invoke the program \n\t./program.exe < input.txt> <output.txt> \n");
exit(1);
}
int i, lines, checker = 0;
Candy *test = NULL;
char* name_test = NULL;
char* candy_test = NULL;
char* line = "Tamar,Apple\n";
int* NumLinesFile = NULL;
Child *ArrayOfChild = NULL;
.
.
.
//GetNumLines check
printf("%s\n", argv[0]);
printf("%s\n", argv[1]);
printf("%s\n", argv[2]);
GetNumLines(argv[1], &NumLinesFile);
lines = *NumLinesFile;
*NumLinesFile = NULL;
printf("%d\n", lines);
//=================================================
//AllocateKidsArray check
//AllocateKidsArray(lines, &ArrayOfChild);
AllocateKidsArray(lines, &ArrayOfChild);
//ImportKidsArray check
ImportKidsArray(argv[1], lines, &ArrayOfChild);
for (i = 0; i < lines; i++) {
//ArrayOfChild[i].candy_of_child = (Candy*) malloc(sizeof(Candy*));
printf("%s,%s\n", ArrayOfChild[i].child_name, ArrayOfChild[i].candy_of_child->candy_name);
}
//=================================================
and im statistically get heap/buffer violation
i suspect this function but i dont know what is wrong with it.
after the init of the array i pass it to another function that fills it in:
int ImportKidsArray(char* file_addr, int num_kids, Child** array_of_kids_to_fill) {
//=================================================
//"ImportKidsArray" reads the file and assign each valid line to cell in the array
//Input: 1. string to a location of a file
// 2. int indicating the number of kids
// 3. pointer to an array of children
//Output: 1. return an int value {0}->Success {-1}->Failure
// 2. pointer to an initialized array of childerns
//=================================================
FILE *fp;
char character;
char line[32];
int i = 0, j = 1, checker = 0, arr_count = 0;
char* TempChild = NULL;
char* TempCandy = NULL;
Child *arr = *array_of_kids_to_fill;
fp = fopen(file_addr, "r");
// Check if file exists
if (fp == NULL) {
printf("Could not open file %s", file_addr);
return -1;
}
while (!feof(fp)) {
fgets(line, 32, fp);
checker = ParseLine(line, &TempChild, &TempCandy);
GetCandy(TempCandy, &(arr[arr_count].candy_of_child));
strncpy((arr[arr_count]).child_name, TempChild, 16);
arr_count++;
}
return 0;
}
please if anyone can help, it will save my life :)
You want to change to ArrayOfChild. Passing it's address from main().
Change it by appropriately de-referencing it.
*ptr_to_childs = malloc(NumOfKids * sizeof(Child));
Then do rest of the operation on *ptr_to_childs. That will retain the change that you made in the called function.
Also check the return value of malloc. And free(using free()) the memory dynamically allocated.
If you notice carefully you will see in the ArrayOfChild() function you are working with a local variable Child **ptr_to_childs. You certainly don't want that as that variable will not be alive when the function ends.
Also while (!feof(fp)) is not appropriate to use. Check this link for that.
Another thing is check the return value of char *fgets(char *str, int n, FILE *stream).
On success, the function returns the same str parameter. If the
End-of-File is encountered and no characters have been read, the
contents of str remain unchanged and a NULL is returned.

Creating an 2D Array of char* an fill it with data from sqlite in callback function

In my function I call the rc = sqlite3_exec(db, sqlStatement, callback, &a, &zErrMsg); function with the callback function.
In this callback function I want to fill a 2D Array of char* with the data from the database.
struct mytable
{
char ***data;
size_t dim;
};
static int callback(void *data, int argc, char **argv, char **azColName)
{
struct mytable *old = (mytable *)data;
char ***temp;
old->dim++;
temp = (char ***)realloc(old->data, old->dim * sizeof(*old->data));
if (temp)
{
old->data = temp;
old->data[old->dim - 1] = NULL;
}
else
{
logging_logError("Kein virtueller RAM mehr vorhanden ... !", __FILE__);
return EXIT_FAILURE;
}
for (int i = 0; i < old->dim; i++)
{
char **temp2 = (char **)realloc(old->data[i], sizeof(argv) * sizeof(*old->data[i]));
if (temp2)
{
old->data[i] = temp2;
old->data[i][argc - 1] = NULL;
}
else
{
logging_logError("Kein virtueller RAM mehr vorhanden ... !", __FILE__);
return EXIT_FAILURE;
}
}
/*Here I try to store the data from each column
in the corresponding position in the 2D array of char* */
for (int i = 0; i < argc; i++)
{
char *s = argv[i];
temp[old->dim - 1][i] = s;
}
return 0;
}
When I print out the data I returned, I get some mysterious signs.
What I want to have is something like this (in array structure):
["1"]["Paul"]["street 1"]["some address"]
["2"]["Anna"]["street asdf"]["some address"]
["3"]["Martin"]["street bfg"]["some address"]
EDIT:
This was my previous question
I don't find it documented specifically, but it seems probable that the argv strings passed into your callback are good only until the callback returns. I don't see how SQLite could work otherwise -- the callback is not responsible for managing the memory for those strings, so SQLite must do so internally.
Therefore, instead of recording the original string pointers in your array, duplicate the strings, and store pointers to the duplicates. MSVC++ provides strdup(), so you might achieve that by replacing ...
char *s = argv[i];
... with ...
char *s = strdup(argv[i]);
. Do be aware that by doing so you assume responsibility for freeing those strings when you're done with them.

return makes integer from pointer without a cast

My goal is to copy strings_operand_table1[i] into label. I would then like to return label to my previous function that called it. How can I fix this and what better ways are there to do this?
char GetBaseDeclarationLabel(char *strings_label_table1[], char *strings_mneumonic_table1[],
char *strings_operand_table1[], int hex_address_table1[])
{
int i = 0;
int cmp_str2 = 0;
char label[20] = {0};
//int k = 0;
//printf(" i is %s \n", strings_label_table1[1]);
for(i = 0; i < 503; i++)
{
if(strings_mneumonic_table1[i] != NULL)`enter code here`
{
cmp_str2 = strcmp(strings_mneumonic_table1[i], "BASE");
if(cmp_str2 == 0)
{
//printf(" ??please?? \n");
//printf(" hex_address_table1[i] is %x \n", hex_address_table1[i]);
strcpy(label, strings_operand_table1[i]);
//label = strings_operand_table1[i];
break;
}
}
}
return label;
}
Edit:
Is this better? If I need to use pointers it seems easier to make the function void and return nothing.
void GetBaseDeclarationLabel(char *strings_label_table1[], char *strings_mneumonic_table1[],
char *strings_operand_table1[], int hex_address_table1[], char *label1)
{
int i = 0;
int cmp_str2 = 0;
//char label[20] = {0};
//int k = 0;
//printf(" i is %s \n", strings_label_table1[1]);
for(i = 0; i < 503; i++)
{
if(strings_mneumonic_table1[i] != NULL)
{
cmp_str2 = strcmp(strings_mneumonic_table1[i], "BASE");
if(cmp_str2 == 0)
{
//printf(" ??please?? \n");
//printf(" hex_address_table1[i] is %x \n", hex_address_table1[i]);
//strcpy(label, strings_operand_table1[i]);
label1 = strings_operand_table1[i];
break;
}
}
}
//return label;
}
Change the return type of the function to a char* AND do not return the address of a local.
Either:
malloc() the memory for label:
char* label = NULL;
/*... snip ... */
if(cmp_str2 == 0)
{
label = malloc(strlen(strings_operand_table1[i]) + 1);
if (label)
{
strcpy(label, strings_operand_table1[i]);
}
break;
}
or avoid memory allocation and simply point label to the matching entry in strings_operand_table1. This is ok as the entries in strings_operand_table1 will exist beyond the scope of the function (and it is simpler for the caller to differentiate between a failed search and failed memory allocation):
char* label = NULL;
/*... snip ... */
if(cmp_str2 == 0)
{
label = strings_operand_table1[i]);
break;
}
Update function return type from char to char*
char GetBaseDeclarationLabel(char *strings_label_table1[], char *strings_mneumonic_table1[],
char *strings_operand_table1[], int hex_address_table1[])
to
char* GetBaseDeclarationLabel(char *strings_label_table1[], char *strings_mneumonic_table1[],
char *strings_operand_table1[], int hex_address_table1[])
Note:
Here you are returning pointer of local array.
See when your function returns that local array's memory will be no longer so returning that pointer is useless.
Use heap memory. Malloc for that array and return pointer of that array and after use do not forget to free it.

Segmentation Fault when accessing string array modified by a function in C

In my main, I define a pointer to an array of filename strings (that are to be determined):
char **commands = NULL;
I then call a function which populates the array based on argc & argv using getopt(). Before I return from the function, I print the list of files in the array and it works fine.
Back in my main, I attempt to print the same list (as confirmation) but I get a segmentation error which I can't figure out how to fix. I've included my code below.
Can someone please help me understand why commands in my main is not able to access the file list.
Cheers,
Nap
Here is the function that builds the list of file names:
int getInput (int argc, char **argv, const char *optionList, int *number, int *showEnds, char **commands, int *numberCommands) {
char c;
opterr = 0; // Turn off automatic error messages.
while ( (c = getopt(argc, argv, optionList)) != -1) {
switch (c) {
case 'n':
*number = TRUE;
break;
case 'E':
*showEnds = TRUE;
break;
case '?':
printf("Invalid switch used \"%c\"\n", optopt);
return EXIT_FAILURE;
break;
default:
printf("Input error occurred");
return EXIT_FAILURE;
}
}
printf("optind = %d,%d\n",optind, argc);
commands = malloc(sizeof(char*) * (argc-1));
if (optind < argc) {
*numberCommands = (argc - optind);
int ndx = 1;
while (optind < argc) {
int arraySize = (ndx+1)*sizeof(char*);
commands = realloc (commands,arraySize);
if (commands == NULL) {
fprintf(stderr,"Realloc unsuccessful");
exit(EXIT_FAILURE);
}
int stringSize = strlen(argv[optind])+1;
commands[ndx] = malloc(stringSize);
if(commands[ndx]==NULL){
fprintf(stderr,"Malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(commands[ndx],argv[optind]);
ndx++;
optind++;
}
printf ("Done With Input\n");
for (int i=1; i<=*numberCommands; i++) {
printf ("%s\n",commands[i]);
}
}
return EXIT_SUCCESS;
}
Here is my main:
int main(int argc, char **argv) {
FILE *myInput;
FILE *myOutput;
int result;
const char availOptions[] = "nE";
// Option flags
int number = FALSE; // (Option n) number all output lines
int showEnds = FALSE; // (Option E) Show Ends
char **commands = NULL;
int numberCommands = 0;
// Set default to stdin/stdout.
myInput = stdin;
myOutput = stdout;
if (argc > 1) {
result = getInput(argc,argv, availOptions, &number, &showEnds, commands, &numberCommands);
if (result != EXIT_SUCCESS) {
exit(EXIT_FAILURE);
}
}
printf ("Number of files = %d\n", numberCommands);
for (int i=1; i<=numberCommands; i++) {
printf ("%s\n",commands[i]);
}
echoInput(myInput, myOutput);
}
You're passing in a copy of the double-pointer
char **commands;
into the function. When you malloc() memory for it, it's not updating the pointer in your main function, only your local copy of the double-pointer. Hence, you're attempting to deference a NULL pointer in main. You could instead pass in a pointer to the double-pointer (i.e. the function would take a triple-pointer), your code would work then.
You would need to dereference the triple-pointer inside the function like so:
*commands = malloc(sizeof(char*) * (argc-1));
Alternatively, make a new double-pointer inside your function, do your work (leaving the code in your function roughly as-is) and before you return, assign the memory back into the pointer passed in from main:
*commands = local_commands;
In this function:
int getInput (/* ... */, char **commands, int *numberCommands) {
/* ... */
commands = malloc(sizeof(char*) * (argc-1));
}
you accept a pointer-to-pointer-to-char parameter by value. Looking at the call site, we can see that value will always be (char**)NULL. The parameter is a local variable inside your function. Even though you change it, and even though the caller happens to have a variable with the same name, you never change the caller's copy.
If you want to change the caller's copy of commands, you need to pass the address of that variable to your function:
int getInput (/* ... */, char ***commands, int *numberCommands) {
/* ... */
*commands = malloc(sizeof(char*) * (argc-1));
}
Now the call site looks like this:
char **commands = NULL;
int numberCommands = 0;
/* ... */
if (argc > 1) {
result = getInput(/*...*/, &commands, &numberCommands);
if (result != EXIT_SUCCESS) {
exit(EXIT_FAILURE);
}
}
note that commands and numberCommands are the two out-parameters - that is, they're the parameters where the function should change your local variable - so you're using & to pass pointers to both of them.

using functions in c (return value)

Learning C and having many doubts.
I have a function (lets say function 1) that calls another function (lets say function 2).
Function 2 calculates an array of string.
How can I use this array in function 1?
Some code example:
int find_errors(char* word)
{
char error[100];
/*Given the word, It will find the duplicate chars and store it in the
error array. */
return 0;
}
int find_word(char* word)
{
find_errors (word);
printf("%s\n", error);
return 0;
}
There are at least three possible approaches:
Use a global variable
pass a parameter between them
return a pointer from the function
There are multiple ways to do this.
1) Create a dynamic array and return a pointer to the array. This will require you to manually free the memory for the array at a later time.
#define NUM_ELEMS 50
// In find_error():
char* error = malloc(NUM_ELEMS * sizeof(char));
return error;
// In find_word():
char *error = find_errors();
// do stuff
free(error);
2) Pass a pointer to find_errors that it can use as the error array. This will not require you to manually free the memory.
// In find_word():
char error[NUM_ELEMS];
find_error(error);
3) Use a global array. May make it more difficult for other people to understand your code. Has other potential problems as well.
// In global scope:
char error[NUM_ELEMS];
Your question relates to "call-by-reference" and "call-by-value".
char* getNewValsToSet(void)
{
char* new_vals = (char*) malloc(sizeof(char[5]));
new_vals[4] = '\0';
return new_vals;
}
void setValuesEven(char* vals_to_set)
{
vals_to_set[0] = 'A';
vals_to_set[2] = 'C';
}
void setValuesOdd(char* vals_to_set)
{
vals_to_set[1] = 'B';
vals_to_set[3] = 'D';
}
int main(void)
{
char* some_vals_to_set = getNewValsToSet();
setValsEven(some_vals_to_set);
setValsOdd(some_vals_to_set);
// ... now has vals "ABCD"
free(some_vals_to_set); //cleanup
return 0;
}
If you have "doubts" about learning C, IMHO it's one of the best things you can do (no matter the language in which you work) because it will explain exactly how things work "under-the-hood" (which all high-level languages try to hide to some degree).
You need to declare the error array globally and use it just like you did.
EDIT: using global variables isn't the best practice in most of the cases, like this one.
Here is an example of what you are looking for with an awesome console output. It dynamically allocates the array to hold any number errors (duplicate characters in your case) that may occur.
//Only free errors if result is > 0
int find_errors(char* word, char** errors)
{
int num_errors = 0;
int word_length = strlen(word);
int ARRAY_SIZE = MIN(8, word_length);
char existing[word_length];
int existing_index = 0;
*errors = NULL;
for(int i = 0; i < word_length; i++)
{
char character = word[i];
//Search array
for (int n = 0; n < word_length; ++n ) {
if(n >= existing_index)
{
existing[n] = character;
existing_index++;
break;
}
if (existing[n] == character) {
num_errors++;
if(!*errors)
*errors = (char*)malloc(ARRAY_SIZE * sizeof(char));
//Check if we need to resize array
if(num_errors >= ARRAY_SIZE)
{
ARRAY_SIZE *= 2;
ARRAY_SIZE = MIN(ARRAY_SIZE, word_length);
char *tmp = (char*)malloc(ARRAY_SIZE * sizeof(char));
memcpy(tmp, *errors, (unsigned long)ARRAY_SIZE);
free(*errors);
*errors = tmp;
}
//Set the error character
(*errors)[num_errors - 1] = character;
break;
}
}
}
return num_errors;
}
int find_word(char* word)
{
char* errors;
int errCount = find_errors (word, &errors);
if(errCount > 0)
{
printf("Invalid Characters: ");
for(int i =0; i < errCount; i++)
{
printf("%c ", errors[i]);
}
printf("\n");
free(errors);
}
return 0;
}
int main(int argc, char *argv[])
{
find_word("YWPEIT");
find_word("Hello World");
find_word("XxxxXXxXXoooooooOOOOOOOOOOOOOOOooooooooOOOOOOOOOOOOooooooOOO");
}

Resources