tPeca* criarPecas(FILE *pFile, int tam){
int i = 0,linhaV,colunaV,j = 0;
char ***elemento = (char***)malloc(tam*sizeof(char**));;
tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca));
if(pecaJogo==NULL)
return NULL;
for(i=0;i<tam;i++){
j=0;
fscanf (pFile, "%[^;]", pecaJogo[i].nome);
fscanf (pFile, ";%d", &pecaJogo[i].qtd);
fscanf (pFile, ";%d", &linhaV);
pecaJogo[i].linha = linhaV;
fscanf (pFile, ";%d", &colunaV);
pecaJogo[i].coluna = colunaV;
**elemento[i] = (char**)malloc(linhaV * sizeof(char*));
*elemento[i][j] = (char*)malloc(colunaV * sizeof(char));
j++;
}
return pecaJogo;
}
*** elemento is a pointer of a matriz, i think that i have problem with malloc... I received Segmentation Fault
These two statements are where I guess you ran into your problem:
**elemento[i] = (char**)malloc(linhaV * sizeof(char*));
*elemento[i][j] = (char*)malloc(colunaV * sizeof(char));
You created char *** above, and attempted to create an array of pointers:
char ***elemento = (char***)malloc(tam*sizeof(char**));;
Should be:
//this step creates an array of pointers
char ***elemento = malloc(tam*sizeof(char*));
//Note: there is no need to cast the return of [m][c][re]alloc in C
// The rules are different in C++ however.
Now you can put elemento in a loop to allocate pointer space for each of the pointers you created:
//this step creates an array pointers for each element of the array created above:
for(i=0;i<tam;i++) //assuming size is also tam (you specified nothing else)
{
elemento[i] = malloc(tam*sizeof(char *));//each ith element will
//now have tam elements of its own.
}
Next, you allocate memory at each location:
for(i=0;i<tam;i++)
{
for(j=0;j<tam;j++)
{
elemento[i][j] = malloc(someValue*sizeof(char));
//Note: sizeof(char) == 1, so could be:
//elemento[i][j] = malloc(someValue);
}
}
Now you have a fully allocated 3D array.
Putting it all together, (A simple 2D example)
When you create memory for a multi-dimensional array, you must create a combination of array of pointers, and memory for each. For 2D example, (used for an array of strings perhaps) you could do this:
char ** allocMemory(char ** a, int numStrings, int maxStrLen)
{
int i;
a = calloc(sizeof(char*)*(numStrings), sizeof(char*));//create array of pointers
for(i=0;i<numStrings; i++)
{
a[i] = calloc(sizeof(char)*maxStrLen + 1, sizeof(char));//create memory at each location
}
return a;
}
You must also create method to free memory:
void freeMemory(char ** a, int numStrings)
{
int i;
for(i=0;i<numStrings; i++)
if(a[i]) free(a[i]);
free(a);
}
Usage:
char **array = {0};
...
array = allocMemory(array, 10, 80);
...
freeMemory(array, 10);
Will create memory, and addresses sufficient to contain 10 arrays of 80 character strings (arrays of char), then free it.
This could be expanded to 3D by adding another layer (for loop) of pointer creation, as shown at top of post). In this implementation, the inner most loop always creates the actual memory for each of the address locations you create.
Related
I'm having trouble accessing my double pointer struct within my structure.
typedef struct monster
{
char *name;
char *element;
int population;
} monster;
typedef struct region
{
char *name;
int nmonsters;
int total_population;
monster **monsters;
} region;
region **
readRegion (FILE * infile, int *regionCount)
{
region **temp;
char garbage[50];
char garbage2[50];
char rName[50];
int monsterNum;
fscanf (infile, "%d %s", regionCount, garbage);
temp = malloc (*regionCount * sizeof (region *));
for (int i = 0; i < *regionCount; i++)
{
fscanf (infile, "%s%d%s", rName, &monsterNum, garbage2);
temp[i] = createRegion (inFile, rName, monsterNum);
}
return temp;
}
region *
createRegion (FILE * inFile, char *rName, int nMonsters)
{
region *r = malloc (sizeof (region));
char rMonster[50];
int rLength;
r->name = malloc ((strlen (rName) + 1) * sizeof (char));
strcpy (r->name, rName);
r->nmonsters = nMonsters;
for (int i = 0; i < nMonsters; i++)
{
r->monsters.name = (nMonsters * sizeof (r->monsters.name));
fscanf (in, "%s", rMonster);
r->monsters.name = malloc ((strlen (rMonster) + 1) * sizeof (char));
strcpy (r->monsters.name, rMonster);
}
return r;
}
Hopefully my code is readable where you can get the jist of what im trying to do with the monster** monsters pointer in my region struct. Any explnation on how to access and use a double struct pointer within a structure would help.
I've tried to clean up and re-interpret your createRegion to read a lot more like traditional C:
region* createRegion(FILE * inFile, char *rName, int nMonsters) {
region *r = malloc(sizeof(region));
char buffer[1024];
r->name = strdup(rName);
r->nmonsters = nMonsters;
r->monsters = calloc(nMonsters, sizeof(monster*));
for (int i=0; i < nMonsters; i++) {
// Allocate a monster
monster *m = malloc(sizeof(monster));
fscanf(in,"%s", buffer);
m->name = strdup(buffer);
m->element = NULL; // TBD?
m->population = 1; // TBD?
// Put this monster in the monsters pointer array
r->monsters[i] = m;
}
return r;
}
Where the key here is you must allocate the monsters. Here it's done individually, but you could also allocate as a slab:
region* createRegion(FILE * inFile, char *rName, int nMonsters) {
region *r = malloc(sizeof(region));
char buffer[1024];
r->name = strdup(rName);
r->nmonsters = nMonsters;
// Make a single allocation, which is usually what's returned from
// C functions that allocate N of something
monsters* m = calloc(nMonsters, sizeof(monster));
// Normally you'd see a definition like m in the region struct, but
// that's not the case here because reasons.
r->monsters = calloc(nMonsters, sizeof(monster*));
for (int i=0; i < nMonsters; i++) {
fscanf(in,"%s", buffer);
m[i].name = strdup(buffer);
m[i].element = NULL; // TBD?
m[i].population = 1; // TBD?
// Put this monster in the monsters pointer array
r->monsters[i] = &m[i];
}
return r;
}
Note I've switched out the highly quirky strlen-based code with a simple strdup call. It's also very odd to see sizeof(char) used since on any computer you're likely to interface with, be it an embedded microcontroller or a fancy mainframe, that will be 1.
Inasmuch as you are asking about accessing a double pointer inside a structure, I think your issue is mostly about this function:
region *
createRegion (FILE * inFile, char *rName, int nMonsters)
{
region *r = malloc (sizeof (region));
char rMonster[50];
int rLength;
r->name = malloc ((strlen (rName) + 1) * sizeof (char));
strcpy (r->name, rName);
r->nmonsters = nMonsters;
[Point A]
So far, so good, but here you start to run off the rails.
for (int i = 0; i < nMonsters; i++)
{
r->monsters.name = (nMonsters * sizeof (r->monsters.name));
Hold on. r->monsters has type monster **, but you are trying to access it as if it were a monster. Moreover, r->monsters has never had a value assigned to it, so there's very little indeed that you can safely do with it.
I think the idea must be that r->monsters is to be made to point to a dynamically-allocated array of monster *, and that the loop allocates and initializes the monsters, and writes pointers to them into the array.
You need to allocate space for the array, then, but you only need or want to allocate the array once. Do that before the loop, at Point A, above, something like this:
r->monsters = malloc(nMonsters * sizeof(*r->monsters)); // a monster **
Then, inside the loop, you need to allocate space for one monster, and assign a pointer to that to your array:*
r->monsters[i] = malloc(sizeof(*r->monsters[i])); // a monster *
Then, to access the actual monster objects, you need to either dererference and use the direct member selection operator (.) ...
(*r->monsters[i]).name = /* ... */;
... or use the indirect member selection operator (->) ...
r->monsters[i]->name = /* ... */;
. The two are equivalent, but most C programmers seem to prefer the latter style.
At this point, however, I note that in the body of the loop, you seem to be trying to make two separate assignments to the monster's name member. That doesn't make sense, and the first attempt definitely doesn't make sense, because you seem to be trying to assign a number to a pointer.
fscanf (in, "%s", rMonster);
r->monsters.name = malloc ((strlen (rMonster) + 1) * sizeof (char));
strcpy (r->monsters.name, rMonster);
Using the above, then, and taking advantage of the fact that sizeof(char) is 1 by definition, it appears that what you want is
// ...
r->monsters[i]->name = malloc(strlen(rMonster) + 1);
strcpy (r->monsters[i]->name, rMonster);
And finally,
}
return r;
}
Note well that corresponding to the two levels of indirection in type monster **, each access to an individual monster property via r->members requires two levels of derferencing. In the expressions above, one is provided by the indexing operator, [], and the other is provided by the indirect member access operator, ->.
* Or you could allocate space for all of the monsters in one go, before the loop, and inside the loop just initialize them and the array of pointers to them. The use of a monster ** suggests the individual allocation approach, but which to choose depends somewhat on how these will be used. The two options are substantially interchangeable, but not wholly equivalent.
I have created double pointer char to be used as a 2d array to store strings. The append function is meant to add the string provided to the end of the array, the num_strings pointer is provided to keep track of the elements in the array (since I can't use sizeof). It seems that at some point, the function isn't allocating enough memory but I can't seem to figure out where and can't find any other issues.
I have already tried giving both the outer array and the inner array large amounts of memory, much more than they need. The issue persists. I have also tried copying the string to the array after the function had run.
int main(int argc, char *argv[]) {
char **strings = NULL;
int num_strings = 0;
append(&strings, &num_strings, "Alex");
append(&strings, &num_strings, "Edward");
// Do things with array
for (int i = 0; i < num_strings; i++) {;
printf("%s\n", strings[i]);
}
// Free memory after use
for (int i = 0; i < num_strings; i++) {
free(strings[i]);
}
free(strings);
strings = NULL;
return 0;
}
void append(char ***array, int * num_strings, char *string) {
if (*array == NULL) {
*array = malloc(sizeof(*array)); // start with enough room for 1 item (pointer)
} else {
// reallocate memory for new item
*array = realloc(*array, (((*num_strings) + 1) * sizeof(*array)));
}
printf("Char Size: %lu\n", sizeof(char));
printf("Given Size: %lu\n", sizeof(***(array)));
*(array[*num_strings]) = malloc((strlen(string) + 1) * sizeof(***(array + 0)));
strcpy(*(array[*num_strings]), string);
(*num_strings)++; // increment the number of strings
}
The output of the program should be the two strings, at the moment it only prints the first and then crashs due to the segmentation fault.
The problem is there are a couple instances of *(array[*num_strings]) that should be (*array)[*num_strings].
The difference is that the first form tries to index through the pointer passed to the function, as if the passed strings were an array, corrupting the caller's stack. The corrected version first derefernces the pointer, then indexed through the target as desired.
There are also a few places where sizeof(*array) is used where it should be sizeof(**array). x = malloc(sizeof(x)) is never correct. But this isn't causing a visible problem.
I have one function, alloc_str, which takes a string pointer and an array of pointers. It dynamically increases the size of the array by one and appends the string into the array. I have run a GDB debugger and highlighted my memory leak and const error below.
My expected input/output:
array = alloc_str(array, "test_1");
array = alloc_str(array, "test_2");
array = alloc_str(array, "test_3");
--> ["test_1", "test_2", "test_3"]
My alloc_str function:
char **alloc_str(char **existing, const char *add)
{
int length = 0; //find the length of the array
for (; existing[length]; length++)
{
}
//allocate memory to copy array array
char **existing_c = (char **)calloc(length + 2, sizeof(char *));
for (int i = 0; i < length; i++) //copy original array into new array
{
existing_c[i] = existing[i];
}
//possible memory leak error
strncat(existing_c, add, sizeof(existing_c) - strlen(existing_c) - 1);
existing_c[sizeof(existing_c)-1] = '\0';
//possible memory leak error
strncpy(existing, existing_c, sizeof(existing - 1));
s_copy[sizeof(destsize)-1] = '\0'; //error here
free(existing);
return existing_c;
}
void free_array(char **strings) //free's data in array, should be fine
{
int length = 0;
for (; strings[length]; length++)
{
}
strings = (char **)calloc(length + 2, sizeof(char *));
}
My main function:
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
int main(){ //should be fine
char **array = NULL;
char **test;
array = (char **)calloc(1, sizeof(char *)); //array has no strings yet
array = alloc_str(array, "test_1");
array = alloc_str(array, "test_2");
array = alloc_str(array, "test_3");
for (test = array; *test; test++)
{
printf("%s\n", *test);
}
free_array(array);
}
My error:
Subscript of pointer to function type 'void (const void *, void *, size_t)' (aka 'void (const void *, void *, unsigned long)')
There are multiple problems:
char **alloc_str(char **existing, const char *add)
{
int length = 0; //find the length of the array
for (; existing[length]; length++)
{
}
//allocate memory to copy array array
char **existing_c = (char **)calloc(length + 2, sizeof(char *));
for (int i = 0; i < length; i++) //copy original array into new array
{
existing_c[i] = existing[i];
}
////////////////////////////////////
//possible memory leak error
strncat(existing_c, add, sizeof(existing_c) - strlen(existing_c) - 1);
existing_c[sizeof(existing_c)-1] = '\0';
//possible memory leak error
strncpy(existing, existing_c, sizeof(existing - 1));
s_copy[sizeof(destsize)-1] = '\0'; //error here
////////////////////////////////////
free(existing);
return existing_c;
}
The part marked with //////////////////////////////////// does not make much sense.
You allocated an array of pointers. Don't treat it like a string. It is no string.
Instead simply assign the new pointer to the end of the array and add terminator again.
existing_c[length] = add;
existing_c[length+1] = NULL;
With that terminater you could use normal malloc instead of calloc because you assign all elements of the array anyway.
Besides the problem with allocation, you have another memory leak:
void free_array(char **strings) //free's data in array, should be fine
{
int length = 0;
for (; strings[length]; length++)
{
}
strings = (char **)calloc(length + 2, sizeof(char *));
}
You pass a pointer to an array of pointers. This array takes some memory that you allocated with calloc earlier.
Then you allocate a bit more memory and assign the address to local variable string.
This has two problems:
The memory that was allocated earlier is not freed.
The memory you allocate in this function is not accessible outside of that function.
In the end, your free_array function does not free anything but consumes more memory.
Another problem might be present with the strings that you store in that array.
In your example you use string literals. These are static objects and there is no need to free them.
If you will use your functions to store pointers to dynamically allocated string as well, you will need to take care about allocating and freeing the strings as well.
strncat() works on a memory buffer containing a NUL-terminated (aka "C") string:
char buf[10] = {'a', 'b', 'c', '\0'};
strncat(buf, "def", sizeof(buf) - strlen(buf) - 1);
assert(strcmp(buf, "abcdef") == 0); // buf now equals to "abcdef"
https://ideone.com/fWXk8C
(Well, the use of strlen() kinda killed the benefit of strncat() over good ol' strcat() but that's another story...)
So it's very different from what you want to do in your exercise. You actually don't need either of strncat() or strncpy().
I'm trying to write a little program which uses realloc(), getchar() and some pointer arithmetic to store an array of characters in the memory.
I have a function called "inputArray" (in convert.c) which receives a pointer to a char (which is NULL to begin with, declared in main.c), then gets reallocated with one char until getchar() gets a '\n' char. the functions seems to work ok, but then when I try to print the string back in main.c, i get a "segmentation fault (core dumped)" error. I've been looking for hours, can't find where the problem is. Thanks!
main.c:
# include "convert.h"
int main()
{
char * string = NULL;
inputArray(string);
printf("%s", string);
free(string);
return 0;
}
convert.c:
#include "convert.h"
void inputArray(char * array)
{
/*pointer to the array*/
char * ptr = NULL;
/*stores the char*/
char c = 0;
/*counter used for pointer arithmetic*/
int count = 0;
/*loop for getting chars in array*/
while ((c = getchar()) != '\n')
{
array = realloc(array, sizeof(char));
ptr = array + count;
*ptr = c;
++count;
}
/*add the null char to the end of the string*/
array = realloc(array, sizeof(char));
ptr += count;
*ptr = '\0';
}
convert.h:
#include <stdio.h>
#include <stdlib.h>
void inputArray(char * array);
The size of the new allocated array is incorrect. You have to allocate count + 1 characters.
array = realloc(array, ( count + 1 ) * sizeof(char));
Take into account that it is more safe to use a temporary pointer to reallocate the memory. Otherwise the original address of the previously allocated memory will be lost.
Also these statements
array = realloc(array, sizeof(char));
ptr += count;
are wrong. You should at least write
array = realloc(array, count * sizeof(char));
ptr = array + count - 1;
Also the function should be declared like
char * inputArray(char * array);
and it must to return the new pointer to the caller.
And in main you have to write
string = inputArray(string);
Otherwise the function should accept the argument by reference that is the parameter should be declared like
void inputArray(char ** array);
and be processed correspondingly in the function.
You are missing one level of indirection in the inputArray function. It should be declared like
void inputArray(char **array)
and it should be realloc'd like this (you also need to increase the size of the array by multiplying with count + 1)
*array = realloc(*array, (count + 1) * sizeof(char));
Call it like this:
inputArray(&string);
I'm relatively new to C in general and I'm having a problem with some code. It's pretty simple code: The objective of the code is to copy a given array of char pointers, or char **source, in other words, to a given char **destination.
The issue I'm having is that sometimes (usually when I have more than 2 strings in source) the first element gets completely corrupted and when I end up printing out destination, it will print out something like ";#?" for the first element, with the other elements printing fine.
The code that performs the copying is:
void CopyArrayOfStrings(char **source, int numStrings)
{
char **destination = malloc(numStrings);
for (int i = 0; i < numStrings; i++)
{
destination[i] = malloc(strlen(source[i] + 1);
strcpy(destination[i], source[i]);
}
}
Note that I left out the code that checks if the result of malloc is NULL.
You need to change your allocation of destination as :
char **destination = malloc(numStrings*(sizeof(char*)));
to allocate number of char * pointers to hold strings.
Also verify you are appropriately passing char ** as source array of strings.
You're doing it wrong.
void CopyArrayOfStrings(char **source, int numStrings)
{
char **destination = malloc(numStrings * sizeof(char *));
for (int i = 0; i < numStrings; i++)
{
destination[i] = malloc(strlen(source[i]) + 1);
strcpy(destination[i], source[i]);
//alternatively you can use strdup() as suggested by #Christoffer
}
}
This will give you storage space for numStrings arrays. Each element of which, will point to a null-terminated string.