I am trying to create buffer to store infinity size of symbols.
I have this structure:
typedef struct buffer {
int bufferSize;
int literalSize;
int allocatedSize;
char *bufferPtr;
} bufferStruct;
In my file.h.
I have also functions for buffer:
bufferStruct *BufferInitialize(int size) {
bufferStruct *tempBuff;
tempBuff = (bufferStruct *)malloc(sizeof(bufferStruct));
if (tempBuff == NULL) {
exit(99); // MEMORY_ERROR
}
tempBuff->bufferSize = size;
tempBuff->literalSize = 0;
tempBuff->bufferPtr = NULL;
tempBuff->allocatedSize = 0;
return (tempBuff);
}
int addToBuffer(bufferStruct *buffer, char c) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
if (buffer->allocatedSize > buffer->literalSize) {
buffer->bufferPtr[buffer->literalSize++] = c;
} else {
buffer->bufferPtr = realloc(buffer->bufferPtr, (buffer->allocatedSize + buffer->bufferSize) * sizeof(char));
if (buffer->bufferPtr == NULL) {
return 99; // MEMORY_ERROR
}
buffer->allocatedSize += buffer->bufferSize;
buffer->bufferSize <<= 1; // bS = bS * 2
buffer->bufferPtr[buffer->literalSize++] = c;
}
return 0;
}
int bufferDestroy(bufferStruct *buffer) {
if (buffer == NULL) {
return 99; // MEMORY_ERROR
}
free(buffer->bufferPtr);
free(buffer);
return 0;
}
In my file.c I am trying to create buffer:
token *getNextToken(token *tokenT) {
token *actualToken = NULL;
char *bufferData = NULL;
int charFromFile;
eState state = stateInit;
bufferStruct *bufferT = NULL;
while ((charFromFile = fgetc(fp))) {
switch (state) {
case stateInit: {
if (isdigit(charFromFile)) {
bufferT = BufferInitialize(8);
addToBuffer(bufferT, charFromFile);
state = stateInt;
} else
if (isalpha(charFromFile) || (charFromFile == '_')) {
state = stateId;
bufferT = BufferInitialize(16);
addToBuffer(bufferT, charFromFile);
} else
if (isspace(charFromFile)) {
state = stateInit;
... some more conditions ... it's similar, a lot.
case stateInt: {
if (isdigit(charFromFile)) {
state = stateInt;
addToBuffer(bufferT, charFromFile);
} else
if ((charFromFile == 'e') || (charFromFile == 'E')) {
state = stateExp;
addToBuffer(bufferT, charFromFile);
} else
if (charFromFile = '.') {
state = stateDouble;
addToBuffer(bufferT, charFromFile);
} else {
bufferData = bufferT->bufferPtr;
//strcpy(actualToken->content, bufferData);
addToBuffer(bufferT, '\0');
bufferDestroy(bufferT);
actualToken->type = tokenInt;
return actualToken;
}
} break;
... other similar cases ...
}
}
}
The problem is when I am trying to do this, Visual studio give me error:
One or more multiply defined symbols found
Also gives me
already defined in main.obj
for every function I have.
I don't see the way out. What am I doing wrong ?
There are multiple issues in your code:
You should not put code in header files. The function BufferInitialize should not be located in file.h unless it is defined inline.
The test while (c = fgetc(fp)) is incorrect: you use an assignment as a test expression, it is very error prone, you should at least parenthesize the assignment expression, and probably test for EOF instead of '\0': while ((c = fgetc(fp)) != EOF). Furthermore, c must be defined as an int. Post actual code, not pseudo-code.
You initialize tempBuff->bufferSize to a potentially non zero value, whereas the allocatedSize is 0 and the buffer is unallocated. This seems incorrect.
There could be many more issues in your actual code, we cannot see what the code, how can be tell you about those? Always post a complete, compilable code that demonstrates the problem.
Related
I have been using libconfig for config files in a project. When I remove the double quotes from sources by source_to_use, config_read_file() returns config_true and also has a syntax error. The syntax error will cause my getter for the source_to_use option to go to the default case. Also because of this my getter for the source array, will also go to the else case. Could this just be me making a simple syntax error with the libconfig format?
This is the config file I am using:
#config for walld
#colors
colors = TRUE;
source_to_use: "sources";
default:
[
"/home/seth/Pictures/kimi.png"
];
sources:
[
"/home/seth/.walld/persona",
"/home/seth/.walld/image-urls"
];
This is the function I have reading it:
settings* read_config(const char* config_file, const char* home_dir) {
settings* options = malloc(sizeof(settings));
config_t config;
config_setting_t* setting;
const char* source;
int colors;
config_init(&config);
if (config_read_file(&config, config_file) == CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
if (config_lookup_bool(&config, "colors", &colors)) {
options->colors = colors;
}
else {
options->colors = 0;
}
if (config_lookup_string(&config, "source_to_use", &source)) {
//NOP
}
else {
source = "default";
}
setting = config_lookup(&config, source);
if (setting != NULL) {
int count = config_setting_length(setting);
linked_node* entry_point = add_node_to_list(NULL, NULL);
linked_node* current = entry_point;
options->sources = entry_point;
for (int i = 0; i < count; i++) {
char* item = config_setting_get_string_elem(setting, i);
current = add_node_to_list(current, item);
}
}
else {
options->sources = malloc(sizeof(linked_node));
int char_count = snprintf(NULL, 0, "%s%s", home_dir, "/.walld/images");
if (char_count <= 0) {
//tough luck
abort();
}
char* default_folder = malloc(char_count + 1U);
if (default_folder == NULL) {
//tough luck
abort();
}
snprintf(default_folder, char_count + 1U, "%s%s", home_dir, "/.walld/images");
options->sources->image = default_folder;
}
config_destroy(&config);
return options;
}
In your read_config function, your first if is:
if (config_read_file(&config, config_file) == CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
The sense of the if is reversed, so you'll return a NULL if the read of the file is valid.
So, you want to reverse the sense of this if:
if (config_read_file(&config, config_file) != CONFIG_TRUE) {
config_destroy(&config);
return NULL;
}
Or you could [probably] use:
if (config_read_file(&config, config_file) == CONFIG_FALSE) {
I am new to C language and I'm trying to compare the characters a pointer points. But when I inspect my code with Intel Inspector for memory errors I am getting invalid memory access errors in this function.
Inspectors says that these two lines cause this.
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
}
Whole function:
bool asteriskControl(char* currentPathParameter) {
int directory = 1;
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
directory++;
}
if (asteriskCounter > directory) {
printf("Can not use '*' operator for the folder that the program is currently in.");
return false;
}
return true;}
This is the line that I call the function.
noAsteriskError = asteriskControl(currentPath);
I am passing currentPath to function and I initialize it here.
char* currentPath = NULL;
char erdem[12] = { 'e','r','d','e','m','/','h','a','k','a','n','\0' };
currentPath = strdup(erdem);
Minimal code example:
int asteriskCounter = 1;
bool asteriskControl(char* currentPathParameter) {
int directory = 1;
for (int i = 0; currentPathParameter[i] != '\0'; ++i) {
if (currentPathParameter[i] == '/')
directory++;
}
if (asteriskCounter > directory) {
printf("Can not use '*' operator for the folder that the program is currently in.");
return false;
}
return true;}
int main() {
char* currentPath = NULL;
char erdem[] = "erdem/hakan";
currentPath = strdup(erdem);
bool noAsteriskError = false;
if (asteriskCounter > 0)
if (currentPath != NULL) {
noAsteriskError = asteriskControl(currentPath);
}
else {
noAsteriskError = false;
}
else {
noAsteriskError = true;
}
return 0;}
Any help is appreciated.
I am trying to implement a circular buffer, I'm writing to it just fine, all the received data is there, but something about my function to read from it doesn't work. No data gets saved into MtoHSdata.
The data I'm trying to read has a Start (>) and End (<) symbol, and is supposed to be sent via USART1.
Read data function:
void MtoHS(struct remoteM *Buff)
{
BYTE k = 0;
static BYTE st = 1;
switch (st)
{
case 1:
{
if ((*Buff).wr != (*Buff).re)
{
(*Buff).re = ((*Buff).re + 1) % (*Buff).max;
if ((*Buff).Buffer[(*Buff).re] == '>') // > == Start Symbol
{
k = 0;
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re];
}
else if ((*Buff).Buffer[(*Buff).re] == '<') // < == End Symbol
{
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re];
st = 5;
}
else
{
MtoHSdata[k] = (*Buff).Buffer[(*Buff).re]; // Data
k++;
}
}
}
break;
/* When End Symbol was read, send data to M */
case 5:
{
BYTE i = 0;
while (MtoHSdata[i] != '<')
{
USART_SendData(USART1, MtoHSdata[i]);
i++;
}
}
break;
default:
{
st = 1;
}
}
return;
}
Write data function (interrupt):
void USART1_IRQHandler(void)
{
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET)
{
uint16_t byteM = 0;
USART_GetITStatus(USART1, USART_IT_ORE);
byteM = USART_ReceiveData(USART1);
pRXD5->Buffer[pRXD5->wr] = byteM;
pRXD5->wr = (pRXD5->wr + 1) % pRXD5->max;
}
return;
}
I'm calling MtoHS function with the parameter 'pRXD5'.
Could anyone please tell me what I'm doing wrong?
this is the function that i am calling from main:
char** readTokens(char *userInput, const char *seperator)
{
char** c;
char line1[512],line2[512];
int wordCount = 0;
int index;
char* tmp;
strcpy(line1, userInput);
for (index=0;line1[index]!='\n';index++);
line1[index]='\0';
strcpy(line2,line1);
tmp = strtok(line1,seperator);
while (tmp!=NULL)
{
tmp=strtok(NULL,seperator);
wordCount = wordCount + 1;
}
if((wordCount) == ERROR)
{
return NULL;
}
c=(char**)malloc(((wordCount)+1)*sizeof(char*));
if (c == NULL)
{
printf("failed to allocate memory.\n");
return NULL;
}
tmp = strtok(line2,seperator);
index=0;
while (tmp!=NULL)
{
c[index]=(char*)malloc((strlen(tmp)+1*sizeof(char)));
if (c[index]==NULL)
{
printf("failed to allocate memory.\n");
return NULL;
}
strcpy(c[index],tmp);
tmp=strtok(NULL,seperator);
index++;
}
c[index] = NULL;//put NULL on last place
return c;
}
And this how i use it in main:
while (fgets(words, sizeof(words), filePointer) != NULL) // this line is a command of reading a line from the file.
{
/*here i am calling the function*/
array = readTokens(words, " ");
theGraph->graphEdges[index_i].sourceVertex = array[ZERO];
theGraph->graphEdges[index_i].destinationVertex = array[ONE];
theGraph->graphEdges[index_i].arcValue = atoi(array[TWO]);
for(index_j = ZERO ; index_j < vertexes ; index_j++)
{
if(theGraph->placeInTableIndex[index_j] == NULL)
{
theGraph->placeInTableIndex[index_j] = array[ZERO];
break;
}
else if(strcmp(theGraph->placeInTableIndex[index_j],array[ZERO]) == ZERO)
break;
}
for(index_j = ZERO ; index_j < vertexes ; index_j++)
{
if(theGraph->placeInTableIndex[index_j] == NULL)
{
theGraph->placeInTableIndex[index_j] = array[ONE];
break;
}
else if(strcmp(theGraph->placeInTableIndex[index_j],array[ONE]) == ZERO)
break;
}
theGraph->graphEdges[index_i+ONE].sourceVertex = array[ONE];
theGraph->graphEdges[index_i+ONE].destinationVertex = array[ZERO];
theGraph->graphEdges[index_i+ONE].arcValue = atoi(array[TWO]);
index_i+= TWO;
//freeTokens(array);
}
I tried to do free to the array in the end of the while but it not work i still have memory leak from this function (valgrind check). i am using this function to free:
void freeTokens(char** tokens)
{
while(*tokens != NULL)
{
*tokens = NULL;
free(*tokens);
*tokens++;
}
tokens = NULL;
free(tokens);
}
You're losing the original value of tokens (the thing you need to free) by incrementing it; then you set it to NULL, then try to free NULL.
Instead:
void freeTokens(char** tokens)
{
char **freeTokens = tokens;
while (*freeTokens != NULL)
{
free(*freeTokens);
*freeTokens = NULL; // not actually necessary, but must happen *after* if at all
freeTokens++;
}
free(tokens);
// tokens = NULL; // accomplishes nothing; doesn't change the caller's version
}
gcc 4.4.3 c89
I have some functions that initialize some hardware and return either true or false. If false then I have to uninitialize in the reverse order.
However, my code is looking very untidy with all the if statements.
For example each function can return either true of false. This is a sample. As you can see the code looks very untidy. I am just looking for any advice on how I can clean it up to make it more manageable and if possible scable?
Many thanks for any advice,
if(init_A() == TRUE) {
if(init_B() == TRUE) {
if(init_C() == TRUE) {
if(init_D() == TRUE) {
if(init_E() == TRUE) {
/* ALL STARTED OK */
}
else {
uninit_A();
uninit_B();
uninit_C();
uninit_D();
}
}
else {
uninit_A();
uninit_B();
uninit_C();
}
}
else {
uninit_A();
uninit_B();
}
}
else {
/* Failed to initialize B */
uninit_B();
}
}
else {
/* Failed to start */
}
if(init_A() != TRUE) {
goto EndA;
}
if(init_B() != TRUE) {
goto EndB;
}
if(init_C() != TRUE) {
goto EndC;
}
if(init_D() != TRUE) {
goto EndD;
}
if(init_E() != TRUE) {
goto EndE;
}
...
return;
EndE: uninitD();
EndD: uninitC();
EndC: uninitB();
EndB: uninitA();
EndA: return;
This is quite a common problem, where the "init" steps correspond to things like malloc() or lock(), and the "uninit" steps correspond to things like free() and unlock(). It is particularly an issue when resources have to be deallocated in strictly the reverse order in which they were allocated.
This is one case where the use of goto is justified:
int somefunc()
{
int retval = ERROR;
if (init_A() != TRUE)
goto out_a;
if (init_B() != TRUE)
goto out_b;
if (init_C() != TRUE)
goto out_c;
if (init_D() != TRUE)
goto out_d;
if (init_E() != TRUE)
goto out_e;
/* ALL STARTED OK */
/* ... normal processing here ... */
retval = OK;
uninit_E();
out_e:
uninit_D();
out_d:
uninit_C();
out_c:
uninit_B();
out_b:
uninit_A();
out_a:
return retval;
}
I would loop through an array of function pointers, call the functions in the loop, then if that function returned false, perform the corresponding uninit_* function.
Here's an example:
void (*inits[5]) (void);
void (*uninits[4]) (void);
int main(void) {
inits[0] = init_A;
inits[1] = init_B;
inits[2] = init_C;
inits[3] = init_D;
inits[4] = init_E;
uninits[0] = uninit_A;
uninits[1] = uninit_B;
uninits[2] = uninit_C;
uninits[3] = uninit_D;
for(int i = 0; i < 5; i++) {
if((*inits[i])() != TRUE) {
int j = (i < 4) ? i : 4;
while(j--) {
(*uninits[j])();
}
break;
}
}
return 1;
}
BOOL a = FALSE, b = FALSE, c = FALSE, d = FALSE, e = FALSE;
if ( (a = init_A()) && (b = init_B()) && (c = init_C()) && (d = init_D()) && (e = init_E()) )
{
}
else
{
if ( e ) uninit_E();
if ( d ) uninit_D();
if ( c ) uninit_C();
if ( b ) uninit_B();
if ( a ) uninit_A();
}
uninit functions are called in direct order, as in your code. If reverse order is required, just change this.
If your uninit_* functions can detect whether or not they need to do anything you can simply:
if (!init_A() || !init_B() || !init_C() || !init_D() )
{
uninit_C();
uninit_B();
uninit_A();
return FALSE;
}
Is that "reverse order"? For me reverse order is like this:
void uninit(int from) {
switch (from) {
/* ... */
case 3: uninit_C(); /* fall_through */
case 2: uninit_B(); /* fall_through */
case 1: uninit_A(); /* fall_through */
case 0: break;
}
}
And the init process would go like this
int count = 0;
if (init_A()) {
count++;
if (init_B()) {
count++;
if(init_C()) {
count++;
if(init_D()) {
count++;
if(init_E()) {
count++;
}
}
}
}
}
if (count == 5) /* ALL OK */;
uninit(count);
Limited understanding of C at work here, if you do decide to downvote, please tell me why.
#include <stdio.h>
int init_a() { return 1; }; // succeed
int init_b() { return 1; }; // succeed
int init_c() { return 0; }; // fail
void uninit_a() { printf("uninit_a()\n"); }
void uninit_b() { printf("uninit_b()\n"); }
void uninit_c() { printf("uninit_c()\n"); }
typedef struct _fp {
int (*init)();
void (*uninit)();
} fp;
int init() {
fp fps[] = {
(fp){&init_a, &uninit_a},
(fp){&init_b, &uninit_b},
(fp){&init_c, &uninit_c}
};
unsigned int i = 0, j;
for(; i < sizeof(fps) / sizeof(fp); ++i) {
if(!(*fps[i].init)()) {
for(j = 0; j < i; ++j) {
(*fps[j].uninit)();
}
return -1;
}
}
return 0;
}
int main() {
init();
return 0;
}
Output:
uninit_a()
uninit_b()
This is the same order that the code in original post would be executed in, but you may want to reverse it (inner loop).
What you perhaps are looking for is "scope bound resource management". C++ traditionally does that with constructors/destructors. But there is a way to do that differently (in C99 as well as in C++) by abusing the for-statement a bit. I wrote something up upon this line here:
scope bound resource management with for scopes.
I've not got a compiler to try this out. But something like this might work?
int (*init[])() = {init_A, init_B, init_C, init_D, init_E};
int (*uninit[])() = {uninit_A, uninit_B, uninit_C, uninit_D, uninit_E};
int main()
{
initfunction(init, 0)
return 0;
}
void initfunction((*init[])(), pos)
{
if(init[pos]() == TRUE)
initfunction(init, pos++)
else
return;
uninit[pos]();
}
int X = 0;
if(init_A() == TRUE) {
X++;
if(init_B() == TRUE) {
X++;
if(init_C() == TRUE) {
X++;
if(init_D() == TRUE) {
X++;
if(init_E() == TRUE) {
X++;
/* ALL STARTED OK */
}
}
}
}
}
/* You said reverse order which I took to mean this,
* though your did not do it this way. */
switch (X) {
case 5:
return SUCCESS;
case 4:
uninit_D();
case 3:
uninit_C();
case 2:
uninit_B();
case 1:
uninit_A();
return FAILURE;
}
Something I find myself doing to prevent myself from making errors in code like this is:
static int do_A(void);
static int do_B(void);
static int do_C(void);
static int do_D(void);
static int do_A(void) {
if (init_A() == FALSE) {
return FALSE;
}
if (do_B() == FALSE) {
uninit_A();
return FALSE;
}
return TRUE;
}
...
static int do_D(void) {
return init_D();
}
All of the other do_ functions should look similar to do_A.