Reputation:
I'm sure I'm just overlooking something simple, but I haven't been able to figure it out. My code is
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h> // For exit()
#include <unistd.h> // for getopt()
const int MAX_PID_LENGTH = 10; // #(PID allowed for user to input)
int main(int argc, char * argv[]) {
int opt; // i.e. option to be parsed
int pidCount = 0; // i.e. #(counted PID)
char ** pidArray;
int pidArrayLength = 10;
while ((opt = getopt(argc, argv, "p:")) != -1) {
switch (opt) {
case 'p':
if (!optarg) {
printf("Invalid command line arguments.\n");
exit(EXIT_FAILURE);
}
if (!pidArray) {
pidArray = (char ** ) malloc(sizeof(char * ) * pidArrayLength);
if (!pidArray) {
printf("Unable to allocate memory.\n");
exit(EXIT_FAILURE);
}
} else if (pidCount >= pidArrayLength) {
pidArrayLength *= 2;
pidArray = (char ** ) realloc(pidArray, sizeof(char * ) * pidArrayLength);
if (!pidArray) {
printf("Unable to reallocate memory./n");
exit(EXIT_FAILURE);
}
}
pidArray[pidCount] = (char * ) malloc(sizeof(char) * MAX_PID_LENGTH);
strcpy(pidArray[pidCount], optarg);
pidCount++;
}
}
}
When I run this code with the command line arguments "-p 1" (or anything else in place of "1"), I get a Segmentation Fault at the line "pidArray[pidCount] = (char *) malloc(sizeof(char) * MAX_PID_LENGTH);". Notably, if I change pidCount in this line to 0, I don't get the Segmentation Fault, even though pidCount has the value 0. Furthermore, when I ssh to one of my school's computer and run the code there, I don't get any such error.
Any insight into what's causing the bug and how to fix it would be greatly appreciated!
Upvotes: 0
Views: 144
Reputation: 67476
pidArray
in if
statement. You need to initialize ot NULL or malloc it in the initializationpidArray = malloc(sizeof(*pidarray) * pidArrayLength);
sizeof(char)
is by definition 1
and is completelly not neededUpvotes: 1