0

I have tried to implement a strings queue in c.

(Queue using an array)

But I get an unknown fly in my code.

1) I try to assign a string to the queue. Is my logic wrong?

static void enqueueInSearchEngineQueue(const char* res_name) {

    if (searchEnginesNamesQueue_ItemsCount <= SEASRCH_ENGINES_QUEUE_MAX_SIZE) {

        *searchEnginesNamesQueue[searchEnginesNamesQueue_ItemsCount] = malloc(sizeof(*res_name));

        strcpy(searchEnginesNamesQueue[searchEnginesNamesQueue_ItemsCount] ,res_name);

        searchEnginesNamesQueue_ItemsCount++;
    }
    else
    {
//      freeSearchEngingeQueue();
    }
}

static int existInSearchEngingeQueue(const char* res_name) {
    int i = 0;
    int answer = 0;

    for (i; i < searchEnginesNamesQueue_ItemsCount; i++) {
        if (strcmp(searchEnginesNamesQueue[i], res_name) == 0) {
            answer = 1;
            break;
        }
    }
    return answer;
}

static void freeSearchEngingeQueue() {
    int i = 0;

    for (i; i < searchEnginesNamesQueue_ItemsCount; i++) {
        free(searchEnginesNamesQueue[i]);
    }

    searchEnginesNamesQueue_ItemsCount = 0;
}

static void searchEnginesIcons_download_callback(const char* res_name,
        int success, void *context, char *last_modified) {
    if (success) {

        if (!existInSearchEngingeQueue(res_name)) {
            enqueueInSearchEngineQueue(res_name);

            #ifdef ANDROID
                        DriveToNativeManager_refreshSearchEnginesIconsOnSearchActivity(res_name);
            #elif defined(IPHONE)
                        //TODO
                        refreshIconsOnSearchActivity();
            #endif
        }
    }
}

2) callbacks from other part of my code fill the queue.

I have thought to use a memory on the stack, would it work or malloc is a must?

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

2

Yes, your code is broken.

You cannot check the length of a string passed to a function as a const char * using sizeof, you need to call strlen(), and add 1 for the terminator to figure out how memory to malloc().

The value of sizeof *res_name is constant, and simply sizeof (char), i.e. 1. So you are overwriting memory wildly, which causes undefined behavior.

unwind
  • 391,730
  • 64
  • 469
  • 606
1

This looks wrong:

*searchEnginesNamesQueue[searchEnginesNamesQueue_ItemsCount] = malloc(sizeof(*res_name));

You don't show the type definition, but the leading * is highly suspicious. Did you really want a dereference there? If that is deliberate, then it looks like it's missing on the following line, and elsewhere.

Also, that's not the way to get a length of a string. Use strlen instead.

Try this:

searchEnginesNamesQueue[searchEnginesNamesQueue_ItemsCount] = malloc(strlen(res_name)+1);
ams
  • 24,923
  • 4
  • 54
  • 75