How to write exact 1MB array in C? - c

I want to initialize an array of size 1MB. So my goal is finally write that 1MB to a file.
I am curious every time i use this formula it is giving less than 1mb.
int len = (1048576)/sizeof(int);
data = (int *) malloc(len);
What is correct way ?
Thank you
Edit - As per the comments I have changed the code .
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
int *data;
int bytes = (1024*1024);
data = (int *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (int)rand();
printf("%d",data[i]);
}
return 0;
}
After compiling it and I tried dumping the data like below
mpicc -o a mpiFileSize.c
./a > dump.dat
Now I see the file size of dump.dat. Why its 2.5MB ?

Try this
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char *argv[]) {
char *data;
int bytes = (1024*1024);
data = (char *) malloc(bytes);
for(int i=0;i<bytes;i++){
data[i] = (char) rand();
printf("%c",data[i]);
}
return 0;
}
You shoul use character instead of integer.

Although it was already properly answered.
Just a plus to the answer, if one wants to choose the amount of MBs to allocate would make something like:
#include <malloc.h>
#define Mebabyte (1024 * 1024)
int main(int argc, char** argv)
{
void* data = malloc(2 * Megabyte);
// Do your work here...
free(data);
return 0;
}
If you wanted to allocate more than 2 MBs just change the 2.
As already stated before do not use integers as it's going to have more than 1 byte of size. Instead use char or unsigned char. And as stated by another post, there's no need to cast the result of malloc since void* can be turned to a pointer to any type (and in fact it's done implicitly by the compiler).
see: Why does this code segfault on 64-bit architecture but work fine on 32-bit?

Related

Understanding double-free mitre.org example

I'm trying to understand the following code example found on mitre:
#include <stdio.h>
#include <unistd.h>
#define BUFSIZE1 512
#define BUFSIZE2 ((BUFSIZE1/2) - 8)
int main(int argc, char **argv) {
char *buf1R1;
char *buf2R1;
char *buf1R2;
buf1R1 = (char *) malloc(BUFSIZE2);
buf2R1 = (char *) malloc(BUFSIZE2);
free(buf1R1);
free(buf2R1);
buf1R2 = (char *) malloc(BUFSIZE1);
strncpy(buf1R2, argv[1], BUFSIZE1-1);
free(buf2R1);
free(buf1R2);
}
They state that it
should be exploitable on Linux distributions
which do not ship with heap-chunk check summing turned on
but they don't explain how. How is it possible?

Storing user-inputted strings into a string array in c?

Fairly new to C, I am trying to read a file of multiple words using bash indirection, and put the words into a string array. The end of the file is marked with a -1.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[400000];
init(words);
int i = 0;
do{
printf("%s",words[i]);
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int i = 0;
do{
fgets(words[i],1024,stdin);
i++;
}while(!strcmp(words[i],"-1"));
}
This gives me a segmentation fault, if any other information is needed I'm more than happy to provide it.
If I guessed correctly, '400000' means the max lines the user can input. But the default size of stack on Windows OS is 1M, sizeof(void*) * 400000 = 1,600,000...
The other thing is that you have not allocated memory for every line.
So, I try to correct your code like this:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINE 4000 // '400000' is really too big!
void init(char* words[]);
int main(int argc,char *argv[]){
char* words[MAX_LINE];
memset(words, 0 , sizeof(words));
init(words);
int i = 0;
do{
printf("%s",words[i]);
delete words[i];
words[i] = nullptr;
i++;
}while(!strcmp(words[i],"-1"));
}
void init(char* words[]){ // initializes array
int maxLen = 1024;
int i = 0;
do{
words[i] = new char[maxLen];
memset(words[i], 0, maxLen);
fgets(words[i], maxLen, stdin);
i++;
}while(!strcmp(words[i],"-1") && i < MAX_LINE);
}

Array with int and char in C

I need to put 3 strings on an array[3][3].
I tried to do it with pointers, but I only receive a single character.
#include <stdio.h>
int array[3][3]
char thing[5] = "thing";
main()
{
thing = array[0][0];
printf("%s", array[0][0];
}
Try this. With due respect your code absolutely incorrect and need many changes. You need to update your programming skills too.
#include <stdio.h>
#include <string.h>
char array[3][6]={0};
char *thing = "this";
main()
{
strcpy(array[0],thing);
printf("%s\n", array[0]);
}

SHA_256 functions corrupting memory space

I've been trying to use the SHA_256 functions in sha256.h on a FreeBSD 9.1 system but it seems to be corrupting memory space of my program causing all kinds of manic behavior. I wrote up a quick program to just to play with those functions and still am having problems.
In the example below, int i is changed when I call SHA256_Init(), as shown by the output from the printf() statements surrounding it.
This is what I get running the code.
$ ./miner "hello world"
i = 0
i = 32
0000000032 9010a9cf81ce2c28a642fd03ddf6da5790c65c30cd4a148c4257d3fe488bacc7
Why is this value changing to 32? Am I missing something? The code is below...
#include <sha256.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#define DIFFICULTY 0
int main(int argc, const char **argv) {
uint nonce, i, j;
SHA256_CTX ctx;
size_t arglen;
unsigned char digest[32];
char * data;
if(argc < 1) exit(1);
arglen = strlen(argv[1]);
data = malloc(arglen + 1);
char digestStr[65];
i = 0;
do {
nonce = i;
strncpy(data, argv[1], arglen + 1);
printf("i = %i\n", i);
SHA256_Init(&ctx);
printf("i = %i\n", i);
SHA256_Update(&ctx, data, arglen);
SHA256_Update(&ctx, (unsigned char *) &nonce, sizeof(nonce));
SHA256_Final(digest, &ctx);
SHA256_End(&ctx, digestStr);
printf("%010i\t%s\n", i, digestStr);
j = 0;
while(j < 32 && digest[j] == '\0') {
j++;
}
i++;
} while(j < DIFFICULTY);
free(data);
return 0;
}
I just had this exact same problem and solved it.
The issue is that your are including a different header in your code than the SHA2 library you linked into your application is using.
In my case the SHA256_CTX struct was a different size in the openSSL library. The openSSL library's struct was 8 bytes bigger than the struct length in the file.
The function SHA256_Init(&ctx) does a memset on the SHA256_CTX struct which then corrupts 8 extra random bytes after the struct. I say random because it will do different things in a release vs debug build because the optimizing compiler will move your variables around.

Realloc 2D array

I'm starting to learn C and would like input characters from a command line and sort them into an array such that the row number is the ASCII character number and the columns are the index of the character from the input. I know that this must be dynamically done via realloc and malloc but I wouldn't know how to code it up. Could someone help me with this problem?
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#define totalASCII 256
int
main(int argc, char **argv) {
int locat;
char current;
int **dRow=NULL;
dRow = malloc(totalASCII*sizeof(*dRow));
for(locat=0;scanf("%c", &current)==1;locat++) {
/* I don't know what to put here */
}
return 1;
}
Your data is so small, there's really no need to allocate it from the heap. Just use an array:
struct { char character; int input_index; } input_data[totalASCII];
On a typical 32-bit system, this will use about 256 * 8 or 2 KB of memory, which really isn't all that much.
Then the storing would be:
for(locat = 0; scanf("%c", &current) == 1; locat++)
{
input_data[locat].character = current;
input_data[locat].input_index = locat;
}
Disclaimer: haven't compiled and run the code.
Try something like this:
int prev_size = 1;
dRow = calloc(totalASCII, sizeof(*dRow)); //use calloc
for(locat=0;scanf("%c", &current)==1;locat++) {
if(dRow[current]) {
prev_size=0;
//try to find how much is already allocated
while(dRow[current][prev_size] != -1)
prev_size++;
dRow[current] = realloc(sizeof(int) * (prev_size+1));
}
else {
prev_size = 1;
dRow[current] = malloc(sizeof(int) * (prev_size+1));
}
dRow[current][prev_size-1] = locat;
dRow[current][prev_size-1] = -1; //end identifier
}
The complexity here is to find the previous allocated size. As there is no other structure/data structure to store this info, this sample code tries to iterate over the array and find -1 which is assumed as end marker.

Resources