0

The program creates a 2D array with malloc and func fills it. fprintf writes in a file. That's all folks.

But I am getting unexpected program exit form the program if I use big integers for height and width.

(30,60): OK

(60,80): not OK

(60,65): OK

(17,41): OK

(200,200): not OK

Does anybody have a clue?

int main() {

    unsigned char **buf = (unsigned char **)malloc(height * sizeof(unsigned char*));
    for (int i = 0; i < height; ++i)
        buf[i] = (unsigned char *)malloc(width * sizeof(unsigned char));

    func(buf);

    FILE * f = fopen("foo.txt", "w+");
    for(int i= 0;i<height;++i)
        fprintf(f, "%s%c", buf[i], '\n');
    fclose(f);

    for (int i = 0; i < height; ++i)
        free(buf[i]);
    free(buf);
}        

void func(unsigned char** buf) {
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j)
            buf[i][j] = 48 + (i/10)%10;
        buf[i][width] = '\0';
    }
}
kurtfu
  • 498
  • 2
  • 4
  • 15
prometeu
  • 679
  • 1
  • 8
  • 23
  • 3
    You need to **allocate space for** `'\0'` – pmg Aug 06 '19 at 08:27
  • 2
    You're mixing `height` and `image_height` as well as `width` and `image_width` – while there isn't a definition visible for any of them. Are you sure they are *all* correctly initialised? – Aconcagua Aug 06 '19 at 08:30
  • 1
    Fyi, [mcve] means we can compile what you posted; we can't for several reasons, not the least of which is missing variables, missing initial values, missing `#include` stack, missing prototype for `func` before first-use. At best you get guesses, and while it may help you out, it makes for lousy answers to help future readers. Please keep this in mind. Also fyi, [don't cast `malloc` in C programs](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Aug 06 '19 at 08:32
  • I translated it wrong, sorry. I will update the question. But @pmg nailed it. – prometeu Aug 06 '19 at 08:35
  • 1
    The solution to that is *don't translate*. Reduce to minimal while still producing your issue, then copy/paste. If you can reproduce with what is posted (and *only* what is posted) then odds are we can too. Thanks. – WhozCraig Aug 06 '19 at 08:35

2 Answers2

2

You need to allocate space for '\0'

buf[i] = (unsigned char *)malloc(image_width * sizeof(unsigned char));

buf[i][width] = '\0';

buf[i][width] does not exist

Try

buf[i] = malloc(image_width + 1);
Community
  • 1
  • 1
pmg
  • 106,608
  • 13
  • 126
  • 198
1

This line writes outside the array.

buf[i][width] = '\0';

You need to allocate one more character.

buf[i] = (unsigned char *)malloc((width + 1) * sizeof(unsigned char));

And make sure to use height and width everywhere.

RobertBaron
  • 2,817
  • 1
  • 12
  • 19