c malloc, why has my array random numbers in it? [duplicate] - c

This question already has answers here:
Is the memory chunk returned by malloc (and its cousins) initialized to Zero?
(6 answers)
What are the contents of the memory just allocated by `malloc()`?
(3 answers)
Closed 5 years ago.
i need to malloc an array with 1000 zeros but when I print it something weird happen
int MAX = 1000;
int *count_array
count_array = (int *) malloc(MAX * sizeof(int));
printf("success?\n");
print_array(count_array,MAX);
but the RETURN looks like:
0 0 0 0 -1973472672 32766 134609 0 857747513 842276920 540291872 540024888 824194871 540293152 892477493 540161824 874525748 809050162 540227104 668466 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 134081 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 133633 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
I really need to get rid of the other numbers, why they are in this array? did I used Malloc wrong?
best regards, Tim4497

malloc() only allocates the memory, it does not zero it. You get whatever was in the memory before (e.g. random noise, or whatever the process that held the memory previously left in there when free()ing the memory -- which could be a safety issue if handling encryption keys and data).
If you need zeroed memory, use calloc().

Related

Understanding malloc(), realloc() and free() in C from reading an output

I need to write an assignement regarding how memory managment is implemented in order to understand what do the few non-zero numbers in the output of this code represent.
I do know that the malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of type void which can be casted into pointer of any form. I also know that if the dynamically allocated memory is insufficient or more than required, you can change the size of previously allocated memory using realloc() function.
Here is the code I have to analyze:
#include <stdlib.h>
#include <stdio.h>
/*** Just playing with the malloc(), realloc(), free()
*** in order to guess how memory management
*** is implemented on this machine. If you get SEGMENTATION
*** FAULT while addressing unallocated memory, just run
*** the program with different "min" and/or "max" values,
*** explicitly given on the command line through argv[]
*** NOTICE: the default values are appropriate for the 32bit systems
*** available in the labs ***/
void showmem (unsigned char *ptr, int min, int max, char name) {
int i;
for (i = min; i < 0; i++)
printf ("%hhu ",ptr[i]);
printf ("*%c=%hhu ",name,*ptr);
for (i = 1; i <= max; i++)
printf ("%hhu ",ptr[i]);
printf ("\n\n");
}
int main(int argc, char**argv) {
unsigned char *p, *q, *o;
int sz=1, min=-8, max=60;
if ( argc > 1 )
sscanf(argv[1],"%d",&sz);
if ( sz <= 0 )
sz = 1;
else if ( sz > 300 )
sz = 300;
if ( argc > 2 )
sscanf(argv[2],"%d",&min);
if ( min > -1 )
min = -1;
else if ( min < -50 )
min = -50;
if ( argc > 3 )
sscanf(argv[3],"%d",&max);
if ( max < sz )
max = sz;
else if ( max > (sz+100) )
max = sz+100;
printf("... allocating %d bytes to p[] (show memory from p[%d] to p[%d])\n\n",sz,min,max);
p = (unsigned char*)malloc(sz);
if ( p == NULL ) {
perror ("Error allocating p\n");
return -1;
}
showmem (p,min,max,'p');
printf("... allocating %d bytes to q[]\n\n",sz);
q = (unsigned char*)malloc(sz);
if ( q == NULL ) {
perror ("Error allocating q\n");
return -1;
}
showmem (p,min,max,'p');
showmem (q,min,max,'q');
sz += 10;
printf("... reallocating p[] to %d bytes (show old p[], new p[], and q[])\n\n",sz);
o = p;
p = (unsigned char*)realloc((void*)p,sz);
showmem (o,min,max,'o');
showmem (p,min,max,'p');
showmem (q,min,max,'q');
sz += 15;
printf("... reallocating p[] to %d bytes\n\n",sz);
p = (unsigned char*)realloc((void*)p,sz); //void e' l'indirizzo di memoria. sz e' la nuova dimensione
showmem (o,min,max,'o');
showmem (q,min,max,'q');
showmem (p,min,max,'p');
sz -= 25;
printf("... reallocating p[] to %d bytes\n\n",sz);
p = (unsigned char*)realloc((void*)p,sz);
showmem (o,min,max,'o');
showmem (q,min,max,'q');
showmem (p,min,max,'p');
printf("... freeing p\n\n");
free((void*)p); `
showmem (o,min,max,'o');
showmem (q,min,max,'q');
showmem (p,min,max,'p');
printf("... freeing q\n\n");
free((void*)q);
showmem (o,min,max,'o');
showmem (q,min,max,'q');
showmem (p,min,max,'p');
printf("... freeing old p\n\n");
free((void*)o);
showmem (o,min,max,'o');
showmem (q,min,max,'q');
showmem (p,min,max,'p');
return 0;
}
And here is the ouput compiling the file without any other inputs:
... allocating 1 bytes to p[] (show memory from p[-8] to p[60])
33 0 0 0 0 0 0 0 *p=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 129 253 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
... allocating 1 bytes to q[]
33 0 0 0 0 0 0 0 *p=0 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0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 0 0 0 0 0 0 0 112 210 6 212 50 86 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0
33 0 0 0 0 0 0 0 *q=112 210 6 212 50 86 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
49 0 0 0 0 0 0 0 *p=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 253 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
... freeing old p
33 0 0 0 0 0 0 0 *o=144 210 6 212 50 86 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 33 0 0 0 0 0 0 0 112 210 6 212 50 86 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0
33 0 0 0 0 0 0 0 *q=112 210 6 212 50 86 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
49 0 0 0 0 0 0 0 *p=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 49 253 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Here is the output while compiling with the input '64':
... allocating 64 bytes to p[] (show memory from p[-8] to p[64])
81 0 0 0 0 0 0 0 *p=0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0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 0 0 0
I did notice how in the memory pointed by q there is a piece of what was pointed by the p one.
What should I focus on while analyzing the output, and most importantly, what do those numbers represent in relation to the definition of malloc, realloc and free?
Thank you in advance for you help.
malloc might allocate more than the n bytes required. It has to do some book-keeping so that e.g. free knows how big the block was in order to fully deallocate it.
It's implementation-specific how malloc does that, either it can prepend each block by some known structure that free,realloc can read like here or it can keep some kind of searchable structure with block information. This is subject to heavy optimizations so it might get quite complicated, try to search for "memory allocation algorithm" or similar.

Golang read byte array from .. to and display result

First of all: I know that this is super basic question and you'd expect to find enough material on the internet and there probably is. I feel pretty stupid right now for not understanding it, so no need to point that out to me - I know^^
From the google Directory API, the response you get when reading a custom Schema is JSON-enocded:
https://developers.google.com/admin-sdk/directory/v1/reference/schemas
I copy/pasted that response and wanted to read it.
func main() {
jsonExample := `
{
"kind": "admin#directory#schema",
"schemaId": "string",
"etag": "etag",
"schemaName": "string",
"displayName": "string",
"fields": [
{
"kind": "admin#directory#schema#fieldspec",
"fieldId": "string",
"etag": "etag",
"fieldType": "string",
"fieldName": "string",
"displayName": "string",
"multiValued": true,
"readAccessType": "string",
"indexed": true,
"numericIndexingSpec": {
"minValue": 2.0,
"maxValue": 3.0
}
}
]
}
`
var jsonDec schemaExample
jsonExampleBytes := []byte(jsonExample)
m := make(map[string]interface{})
err := json.Unmarshal([]byte(jsonExample), &m)
byteStorage := make([]byte,600)
byteReader := bytes.NewReader(byteStorage)
res, err := byteReader.ReadAt(jsonExampleBytes,50)
fmt.Printf("############Hier : %v Err: \n%v",res,err)
fmt.Printf("Storage: %v\n",byteStorage)
byteStorage := make([]byte,600)
byteReader := bytes.NewReader(byteStorage)
res, err := byteReader.ReadAt(jsonExampleBytes,50)
fmt.Printf("Result : %v Err: %v\n",res,err)
fmt.Printf("Storage: %v\n",byteStorage)
This returns
res : 526 Err: <nil>
Storage: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
.My question is how to implement a ReadFromTo method, which allows me to read a specific range of bytes from a byte array? And since the storage is empty, I also lack to understand how read that array back at all with the reader functions, only way I know how to pull it off is this:
fmt.Printf("Und die bytes to String: %v",string([]byte(jsonExample)))
From the docs (emphasis mine):
ReaderAt is the interface that wraps the basic ReadAt method.
ReadAt reads len(p) bytes into p starting at offset off in the underlying input source.
type ReaderAt interface {
ReadAt(p []byte, off int64) (n int, err error)
}
The argument to ReadAt (and Read in general) is the destination. You've got jsonExampleBytes and byteStorage the wrong way around.
package main
import (
"bytes"
"fmt"
)
func main() {
jsonExampleBytes := []byte(`{...}`)
byteReader := bytes.NewReader(jsonExampleBytes)
byteStorage := make([]byte, 600)
n, err := byteReader.ReadAt(byteStorage, 3)
fmt.Println("Storage:", string(byteStorage[:n]), err) // Storage: .} EOF
}
To access a sub-slice of bytes, you can in the most basic case just use the index operator:
array := make([]byte, 100)
bytes5to9 = array[5:10]
note here that the second index is exclusive.
If you need an io.Reader from these bytes, you can use
r := bytes.NewReader(array[5:10])
You can do this again, creating a second read for the same or a different range of the array.
The utility functions in io and ioutil might be of interest to you as well. See for example ioutil.ReadAll, io.Copy, io.CopyBuffer, io.CopyN and io.ReadFull.

How to read in a specific number with sscanf from lines which are similar?

I'm trying to read in a specific number from a file with the sscanf()function in the C standard library. My example data comes from /proc/stat on a system running a Linux Kernel. Here is how it looks:
cpu 90158 11772 50095 6885572 36975 0 207 0 0 0
cpu0 22942 2975 12847 1720241 9655 0 58 0 0 0
cpu1 23879 2979 12080 1717405 12483 0 45 0 0 0
cpu2 21510 3105 12864 1722238 7790 0 57 0 0 0
cpu3 21824 2712 12301 1725687 7044 0 45 0 0 0
.
.
.
intr 2108705 19 28724 0 0 0 0 0 0 1 90871 0 0 204911 0 0 0 143 0 0 0 0 35 0 0 0 0 2362 0 101810 25 388 0 404786 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 11136028
btime 1423918994
processes 155184
procs_running 2
procs_blocked 1
softirq 2109698 8 644880 168 19330 95660 0 24557 551780 3897 769418
I try to print all lines after the if-statement except those lines containing cpu directly followed (without a whitespace) by a number. That is the first line cpu should be printed with all the others but e.g. not the second line cpu0. Furthermore, the number directly following cpu in these lines should be stored as an int into int cpu.
I really tried to get my head around this and I can at least get the correct lines to print by using character classes. My if-statement contains:
sscanf(line, "cpu%*1[^ ]%d", &cpu) != 1)
where %1[^ ] means read in the line until you encounter a single whitespace (the 1 is probably not needed) and then store the following number %d in int cpu. But the wrong values are stored for the cpuN-lines. Instead of storing 0, 1, 2, 3 the values 22942, 23879, 21510, 21824 are stored. Now this can be traced back to my usage of %1[^ ]. But I tried so many different things that I might be missing the obvious. How can I print all lines except the ones where cpu is followed (without a whitespace) by a number N and storing N in int cpu? (I'd like to avoid using regex.h if possible.) Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
fp = fopen("/proc/stat", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
int cpu;
if (sscanf(line, "cpu%*1[^ ]%d", &cpu) != 1) {
printf("%s", line);
}
}
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
You do not want to suppress the assignment of the digit after cpu. However, you also don't want to skip blanks, so you need to use either %c or %[] since all other formats (other than %n, which definitely doesn't count in this contex) skip leading blanks. That, in turn, means you need to read a character string, not an integer. So, the code should be:
char cpu_str[8]; // Allow for big machines!
if (sscanf(line, "cpu%7[^ ]", cpu_str) != 1)
printf("%s", line);
else if (sscanf(cpu_str, "%d", &cpu) != 1)
…oops: may the scanset should be %7[0-9]…
else
…cpu contains the cpu number…
suggest:
1) read line into buffer
2) strncmp (buffer, "cpu ") if 0, ignore line // notice trailing space
3) strncmp (buffer, "cpu" ) if 0, saved = atoi( buffer[3] ) // no trailing space
4) ignore all other lines

How to diminish CPU usage in linux c application (detached multithread)?

I eager to know which situation makes increased cpu-usage in checking top information to process written by me.
below is my environment.
# cat /proc/cpuinfo
system type : CN3010_EVB_HS5 (CN5010p1.1-500-SCP)
processor : 0
cpu model : Cavium Octeon+ V0.1
BogoMIPS : 1000.00
wait instruction : yes
microsecond timers : yes
tlb_entries : 64
extra interrupt vector : yes
hardware watchpoint : yes, count: 2, address/irw mask: [0x0ffc, 0x0ffb]
ASEs implemented :
shadow register sets : 1
kscratch registers : 0
core : 0
VCED exceptions : not available
VCEI exceptions : not available
# cat /proc/softirqs
CPU0
HI: 0
TIMER: 37673
NET_TX: 1
NET_RX: 63481
BLOCK: 0
BLOCK_IOPOLL: 0
TASKLET: 241456
SCHED: 0
HRTIMER: 0
RCU: 45060
#
# cat /proc/stat
cpu 6890 0 7591 11217 324 691 17637 0 0
cpu0 6890 0 7591 11217 324 691 17637 0 0
intr 3872174 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3557213 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 30852 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2530 0 6328 275165 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 88 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 7152106
btime 1387517330
processes 1956
procs_running 2
procs_blocked 0
softirq 454085 0 44350 1 74147 0 0 282595 0 0 52992
**Cpu(s): 20.6%us, 23.0%sy, 0.0%ni, 15.0%id, 0.0%wa, 2.2%hi, 39.3%si, 0.0%st**
Mem: 45220K used, 50560K free, 0K shrd, 0K buff, 17568K cached
Load average: 0.52 0.72 0.52
PID USER STATUS RSS PPID %CPU %MEM COMMAND
800 root S 5076 1 75.3 5.2 core
2104 root S 2448 848 0.0 2.5 sshd
....
--> core is my process(with multithread) that has about 22 threads for doing jobs.
shortly, one thread to collect wireless packet, one thread changes wifi-frequency using netlink library. I'm not sure but I think that makes increased cpu-usage.
I don't know to control this situations, how to approach,
Which part do I check?
below is my thread style.
while(1) {
do jobs;
sleep(x);
}
--> switched to
while (1) {
sleep(x);
do jobs;
}
Can't resolve it. How to handle this issue? which part do I check ?
Please help me. I don't want to upgrade CPU.
You would generally use a profiler to determine where your application is spending its time.
Newer Linux kernels have a very low overhead profiler built in, which can trace in and out of kernel space as well, named perf. You can perf record your application and then run perf report to see what it did.
It seems you are using OCTEON+ CN5010 cpu. As an advanced perf improvement task, you could utilize OCTEON simple-exec programs (on Linux, or on separate cores natively), to get a further performance boost.
Paxym

Unexpected data/unexpected segfault in a dynamically allocated array (for two dimensional use)

I am trying to create a 2D matrix in C (basically a dynamically allocatable 2d array of any given size) in both the most efficient and clean way possible. I had implemented such a thing in a larger project I am working on, but was having issues, and was able to narrow it down to the following.
I decided to malloc a giant array (I called it data), and then make an array of pointers (i called it cell) to be able to address the data in the big array in such a way that would make sense in a two-dimensional context (as in matrix[x][y] instead of data[ugly pointer arithmetic each time].) I thought this would be a good idea because it only calls malloc once, and so it would be faster, also, the allocated memory is in one consecutive block, which I believe (not too knowledgeable here) is a really good thing on some systems because of overhead in keeping track of allocated memory blocks.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef struct {
unsigned int sizeX;
unsigned int sizeY;
int **cell;
int *data; /* FOR INTERNAL USE ONLY */
} matrix;
matrix * matrix_malloc(unsigned int, unsigned int);
void matrix_free(matrix *);
void matrix_zero(matrix *);
void matrix_print(matrix *);
int
main(int argc, char *argv[])
{
int y, x;
matrix *theMatrix = NULL;
if (argc != 3) {
fprintf(stderr, "usage: %s sizeX sizeY\n", argv[0]);
return 1;
}
x = atoi(argv[1]);
y = atoi(argv[2]);
if (x < 10 || y < 10) {
fprintf(stderr, "usage: sizeX and sizeY must be >= 10\n");
return 1;
}
if ((theMatrix = matrix_malloc(x, y)) == NULL)
return 1;
matrix_zero(theMatrix);
/* lots of modification of the contents of the matrix would happen here */
matrix_print(theMatrix);
matrix_free(theMatrix);
return 0;
}
matrix *
matrix_malloc(unsigned int sizeX, unsigned int sizeY)
{
int i;
matrix *mat;
if ((mat = malloc(sizeof(matrix))) == NULL) {
return NULL;
}
if ((mat->data = malloc(sizeX * sizeY * sizeof(int))) == NULL) {
free(mat);
mat = NULL;
return NULL;
}
if ((mat->cell = malloc(sizeX * sizeof(int *))) == NULL) {
free(mat->data);
free(mat);
mat = NULL;
return NULL;
}
mat->sizeX = sizeX;
mat->sizeY = sizeY;
for (i = 0; i < sizeX; i++) {
mat->cell[i] = mat->data + mat->sizeX * i;
}
return mat;
}
void
matrix_free(matrix *mat) {
free(mat->cell);
free(mat->data);
free(mat);
mat = NULL;
}
void
matrix_zero(matrix *mat)
{
memset(mat->data, 0, mat->sizeX * mat->sizeY * sizeof(int));
}
void
matrix_print(matrix *mat)
{
unsigned int x, y;
for (x = 0; x < mat->sizeX; x++) {
for (y = 0; y < mat->sizeY; y++)
printf("%d ", mat->cell[x][y]);
printf("\n");
}
}
When I run the above program as ./a.out 10 10 there is no problem, but when I specify 30 20 instead of 10 10, I run into some issues.
On MacOSX (10.6.7) I get:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 540024880 540024880 540024880 540024880 540024880 808465461 943207474 875896880 875704368 540031032
842216505 926168880 926425140 909719605 540031032 926234424 909325360 875896888 825438256 540160816 10 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0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0 0 0 0 0 0 0 0 0
and then it just segfaults
My initial thought was that it was just some issue when allocating big enough blocks of memory that they cross page boundaries, but when I use 50 50 as the size, it runs fine.
I've narrowed it down this far, and tried googleing (not quite sure what it is I should be searching for though :| ) and asked a few of my friends, but this has them all stumped.
I found C. Segmentation Fault when function modifies dynamically allocated 2d array int matrix with pointers in C - memory allocation confusion but they were not relevant (as far as I can tell).
If somebody could please point me in the right direction, perhaps point out the problem or point me to some relevant documentation, I would be very grateful.
for (i = 0; i < sizeX; i++) {
mat->cell[i] = mat->data + mat->sizeX * i;
}
One of these SizeX'es needs to be a sizeY.
for (i = 0; i < sizeX; i++) {
mat->cell[i] = mat->data + mat->sizeX * i;
}
Imagine if sizeX is 100 and sizeY is 2. Here, you're laying out sizeX rows, 100 of them, each sizeX integers, 100 of them. Ooops.
That mat->sizeX should be mat->sizeY. You have sizeX rows, each with sizeY elements in them. So you need to skip forward sizeY integers to get to the next row.

Resources