-2

I tried to read binary files into dinamic string and somthing go wrong. I cant set free the string and i cant print or do anything else with it. The files are OK if I just open it without all the dinamic stuff it runs well.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#pragma warning (disable: 4996)

#define STR_LEN 50

int main(int args, char** argv)
{
    char filePath[STR_LEN];
    char signaturePath[STR_LEN];
    FILE* file;
    FILE* signature;
    int fileSize;
    int signatureSize;

    strcpy(filePath, argv[2]);
    strcpy(signaturePath, argv[1]);

    file = fopen(filePath, "rb");
    signature = fopen(signaturePath, "rb"); 

    if (file == NULL)
        printf("e:  f\n");
    if (signature == NULL)
        printf("e:  s\n");

    fseek(file, 0L, SEEK_END);
    fileSize = ftell(file);
    fseek(file, 0L, SEEK_SET);

    fseek(signature, 0L, SEEK_END);
    signatureSize = ftell(signature);
    fseek(signature, 0L, SEEK_SET);

    char* fileStr = (char)malloc(sizeof(char) * fileSize + 1);
    char* signatureStr = (char)malloc(sizeof(char) * signatureSize + 1);

    fread(fileStr, fileSize, 1, file);
    fread(signatureStr, signatureSize, 1, signature);



    free(fileStr);
    free(signatureStr);
    fclose(file);
    fclose(signature);

    return 0;
}

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • 1
    Just as a point, *never* access `argv[]` until you have checked the element's validity with `args.` Unless people show that, I won't believe they provided any arguments. – Weather Vane May 20 '21 at 15:37
  • 1
    Another point: Don't declare `filePath` and `signaturePath` as arrays. There is no need to copy the strings pointed to by `argv[1]` and `argv[2]`. Just declare the path variables as `const char *` and have them point to the same strings as `argv[1]` and `argv[2]`. That way you are not limited to 49 character long path names, and you don't have to worry about complex code to prevent buffer overflows. – HAL9000 May 20 '21 at 15:45
  • thanks. very helpful. – אלינר בן דוד May 20 '21 at 16:52

1 Answers1

3

You are casting the pointers that malloc() returns to char. In typical environment, char is 1-byte long while pointers are 4-byte or 8-byte long. The cast will truncate the pointers, turning them to some invalid value.

Casting results of malloc() family is considered as a bad practice. Remove the harmful casts to fix.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70