0

I have the following C code:

  char buffer[255];
  char ***data = NULL;
  int i = 0;
  int size = 10;

  **data = (char*) calloc(size, sizeof(char**));

  while(fgets(buffer, 255, database)) {
    if(i + 1 >= size) {
      size += 10;
      **data = (char*) realloc(**data, size*sizeof(char**));
    }

    char **line = str_split(buffer, ',', 6);
    **data[i++] = **line;
  }

I am a noob at C. And I do not rearly understand my code. But I want a 3D char array (in Java I woud say a 2D String array). The first [] are the lines from my textfile reading with 'fgets' from 'database' (and I don't know how many lines, thats why I want it dynamic). The second [] and thirt [] are filled with the values from str_split.

str_split works fine, thats the code:

char** str_split(char* str, const char a_delim, int count) {
  char **result;
  char  *token;
  char  *rest = str;
  char  delim[] = { a_delim, '\0' };

  result = (char**) malloc(sizeof(char*) * count);

  int i = 0;
  while((token = strtok_s(rest, delim, &rest))) {
    *(result + i++) = token;
  }

  return result;
}

So the problem is at run time I get the following error:

Access violation writing location 0x00000000.

What is wrong?

7
  • 1
    1) **data = (char*) calloc(size, sizeof(char**)); --> data = (char***) calloc(size, sizeof(char**)); Commented Jan 5, 2016 at 15:46
  • "I do not rearly understand my code": Then how did you write it? And where is this error occurring? Commented Jan 5, 2016 at 15:46
  • "I do not nearly understand my code" Well, that's frustrating. How can you expect others to understand it? Commented Jan 5, 2016 at 15:46
  • @BLUEPIXY Do you have some "2)" ? Commented Jan 5, 2016 at 15:49
  • @EugeneSh. yes, 1,2,3... Commented Jan 5, 2016 at 15:51

1 Answer 1

2

The first alloc should look like:

data = (char***) calloc(size, sizeof(char**));

Similar for realloc, and finally

data[i++] = line;

The problem is that you try to dereference data (**data) to assign it the value of the calloc, but data is null to begin with so you get access violation. In general you should make sure that a pointer is not null before you deference it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.