ncpa0cpl
ncpa0cpl

Reputation: 192

Strange behaviour in C program, variable corruption after allocating memory

I have typdef of string in my C program, it looks like that:

#define WRD_LEN 100
typedef char cstring[WRD_LEN];

then at some point I declare dynamic array of this type:

int pcount = 1;
cstring *options = malloc(sizeof(cstring*)*pcount);

I add new strings to this array with use of realloc:

options = realloc(options, sizeof(cstring*)*pcount);
strcpy(options[pcount-1], //some string//);
pcount++;

and then show all entries to user, user choses one of them and that one is passed to another function:

highestof(mode, l, options[btn]);

mode is an integer, l is struct but those are irrelevant now. btn is number (int) of entry chosed by user. Up to this point everything works just fine, problem shows up inside highestof function:

void highestof(const int mode, List l, const cstring cat) {
List *p = malloc(sizeof(List*));

here is definition of List:

struct W {
    //some data
    struct W *next;
};
struct List {
    struct W *first;
};

So if highestof function is called with options[1], cat variable will get corrupted (it will became a set of few random symbols, like "#^?" or "^K^?") right after malloc is called i.e. before creating dynamic array of List I can use cat as much as I want, but after calling malloc it gets corrupted. Most strange thing about this is that it happens only if variable passed down to this function was in options array under index of 1 (options[btn] where btn = 1) For any other value of btn it works no problem.

I found a workaround for this, I can create a string (char s[100]) before calling malloc, copy cat value into it and use that variable instead, but it's really not resolving initial problem and it really bothers me.

Upvotes: 0

Views: 105

Answers (2)

gnasher729
gnasher729

Reputation: 52538

cstring* is just a pointer, usually four or eight bytes. sizeof (cstring*) is therefore a small number, usually four or eight.

You are not allocating enough memory for the data, just enough memory to hold pointers to the data.

Upvotes: 1

chux
chux

Reputation: 153457

sizeof(cstring*)*pcount is too small. The size calculation is amiss.


Avoid allocation errors. Use this idiom for code that is easier to write correctly, review and maintain.
Notice no type is used.

pointer = malloc(sizeof *pointer * n);

Then code becomes:

// options = malloc(sizeof(cstring*)*pcount);
options = malloc(sizeof *options * pcount);`

Upvotes: 3

Related Questions