Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Memory management in C

Name: Anonymous 2013-02-17 18:50

I'm trying to create an array (or technically pointer but I'm just gonna call it array from here on out because that's what I'm used to) that's just large enough to hold whatever is entered at the command line (except for the program name, obviously). The relevant code looks something like this:

int numCount = argc -1
int *num

num =(int*) malloc(numCount * sizeof(int))

after that I check if its null and then initialize it as so

memset(num, 0, numCount)


The problem that I'm running into is that the array seems to be much bigger than necessary. Also if I give 5 numbers at the command line and do a diagnostic print of num[6] I get a segmentation fault, but if I print num[7] or num[8] and so on, which also shouldn't exist I would think, it will be fine and print out a 0. I'm not used to programming in C or on Linux at all so I'm sure whatever I fucked up is something obvious, it would be nice to get a little help here.

Name: Anonymous 2013-02-17 19:04

>>1
I'm not going to be able to help you to the end of what you are trying to do, but memset(num, 0, numCount) ought to be memset(num, 0, numCount*sizeof(int)).

That third argument is the size of the block of memory, the same value that you gave to malloc.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List