I have a question on a simple program that i wrote to initialize an array one element at a time, the few lines of code are below:
#include <stdio.h>
int main(void)
{
int *ptr;
int index;
for (index = 0; index < 4; index++)
{
ptr[index]=index;
printf("%d\n", ptr[index]);
}
return 0;
}
All plain and simple but when I run the program I incur in segmentation fault (core dumped) error, that to my understanding occurs when you try to write on something that is only readeable or if you have exceeded your allowed memory...
Excuse me for this probably nobbish question but I could not find a similar question on SO.
You cannot just use int *ptr and treat it as an array. You need to actually create an array and allocate space for it, by specifying the size. You can either make it as an array like in the first option, or allocate it using malloc() in the second option. I suggest the first one because it executes faster, and it seems your array is of fixed length. The second option is for applications where you do not know the array size until runtime.
#include <stdio.h>
int main(void)
{
int ptr[4]; //you need to specify array size first
int index;
for (index = 0; index < 4; index++)
{
ptr[index]=index;
printf("%d\n", ptr[index]);
}
return 0;
}
You can also use malloc() if you want to allocate it on the heap, but make sure to free() it, to free the memory, or there will be a memory leak.
#include <stdio.h>
int main(void)
{
int *ptr = malloc(4*sizeof(int));
int index;
for (index = 0; index < 4; index++)
{
ptr[index]=index;
printf("%d\n", ptr[index]);
}
free(ptr);
return 0;
}
This should solve your problem
Also you don't need a for loop to initialize populate the values of the array, in case that is what you are trying to do. You can do this:
int ptr[4] = {0, 1, 2, 3};
As stated in #ChristianGibbons comment, you just need to allocate memory for the array the address of your pointer.
#include <stdio.h>
int main(void)
{
int sizeOfArray = 4;
int *ptr = calloc(sizeOfArray, sizeof(int)); // line to fix
int index;
for (index = 0; index < sizeOfArray; index++)
{
ptr[index]=index;
printf("%d\n", ptr[index]);
}
free(ptr);
return 0;
}
Related
I need to create an array of strings, each representing a card of the Spanish deck:
#define __USE_MINGW_ANSI_STDIO 1
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char *type[4]= {"copas", "basto", "espada", "oro"};
char *number[10]= {"Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce"};
char *deck[40];
int deckIndex= 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 10; j++) {
char card[100] = "";
strcat(card, number[j]);
strcat(card, " de ");
strcat(card, type[i]);
strcat(card, "\n");
deck[deckIndex]= card;
deckIndex++;
}
}
for (int i = 0; i < 40; i++)
{
printf("%s\n", deck[i]);
}
return 0;
}
However, all entries of deck[] point to the same string. As a result, "Doce de oro" is printed 40 times. I don't understand why this happens, but I've theorized it's because card[] is being reinitialized in the same memory direction, and overrides what was already written there in the previous iteration. If I'm right, I would have to declare every array separately, but I have no idea how to do that without writing 40 different arrays.
Tldr:
¿Why do all entries of deck[] point to the same location?
¿How do I fix it?
(Btw suggestions for a better title are appreciated)
In C, memory on the stack is allocated in terms of Scopes. So yes, your theory is right. You are rewriting on the same location.
To fix your program, there are two possible solutions I can think of.
You can use Multidimensional Arrays.
Or you can allocate memory in heap using malloc (but make sure to free it once you are done with it)
As pointed out in the comments, in the deck[deckIndex]= card; line, you are assigning the same pointer1 to each of your deck elements – and, worse, a pointer to a variable (the card array) that is no longer valid when the initial nested for loop goes out of scope.
To fix this, you can make copies of the card string, using the strdup function, and assign the addresses of those copies to the deck elements. Further, as also mentioned in the comments, you can simplify the construction of the card string using a single call to sprintf, rather than using multiple strcat calls.
Here's how you might do that:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char* type[4] = { "copas", "basto", "espada", "oro" };
char* number[10] = { "Uno", "Dos", "Tres", "Cuatro", "Cinco", "Seis", "Siete", "Diez", "Once", "Doce" };
char* deck[40];
int deckIndex = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
char card[100] = "";
sprintf(card, "%s de %s", number[j], type[i]);
deck[deckIndex] = strdup(card);
deckIndex++;
}
}
for (int i = 0; i < 40; i++) {
printf("%s\n", deck[i]);
}
// When you're done, be sure to free the allocated memory:
for (int i = 0; i < 40; i++) {
free(deck[i]);
}
return 0;
}
If your compiler does not support the strdup function (most do, and it is part of the ISO C Standard from C23), writing your own is very simple:
char* strdup(const char *src)
{
char* result = malloc(strlen(src) + 1); // Add one to make room for the nul terminator
if (result) strcpy(result, src);
return result;
}
1 Well, formally, a new card array is born on each iteration of the inner for loop, but it would be a very inefficient compiler that chose to do that, rather than simply re-using the same memory – which is clearly what is happening in your case.
I just have a function that finds out the maximum value of an array of integers, but I get a segmentation fault, which I can't find because the compiler doesn't show me the line of the error.
This is my C code:
#include <stdlib.h>
#include <stdio.h>
//Funktion ermittelt den größten Wert eines Arrays
int groesstesElement(int **arrayPointer){
int max = 0;
for (int i = 0; i < 3; i++) {
if (*arrayPointer[i]>max) {
max = *arrayPointer[i];
}
}
return max;
}
int main (int argc, char **argv) {
int array[4]={1,2,3,4};
int *ptr = array;
int z = groesstesElement(&ptr);
printf("%d\n", z);
return EXIT_SUCCESS;
}
I use macOS and VSC.
In C, array indexing [] has higher precedence than pointer de-referencing *: https://en.cppreference.com/w/c/language/operator_precedence
Some parentheses fix the segfault.
if ((*arrayPointer)[i]>max) {
max = (*arrayPointer)[i];
}
Due to the operators precedence, with
*arrayPointer[i]
you are telling your program:
Take the i-th element of the array arrayPointer and dereference it.
But arrayPointer is a pointer to int *, so all you get is the address of ptr (the int ** pointer defined from main) with an offset. When you finally dereference it you are likely accessing an invalid address, causing segmentation fault.
As already suggested by the main answer, the fix is done using parenthesis in order to apply the operators in the order you want:
(*arrayPointer)[i]
Secondary issues in the code
Even though with the correction above the program won't crash anymore, it won't work. Searching through the array with the loop
for (i = 0; i < 3; i++)
you won't include the last item in the search (index 3), skipping precisely the index that, in your example, contains the maximum value. You probably meant for (i = 0; i < 4; i++) or for (i = 0; i <= 3; i++).
Anyway, using magic numbers in the code (in this case the dimension of the array) is considered bad practice. A better solution would have been using a #define, but an even better solution would have been passing to the function the size of the array:
#include <stdlib.h>
#include <stdio.h>
#define ARR_SIZE 4
//Funktion ermittelt den größten Wert eines Arrays
int groesstesElement(int *arrayPointer, unsigned int arrSize){
int max = 0, i;
for (i = 0; i < arrSize; i++) {
if (arrayPointer[i]>max) {
max = arrayPointer[i];
}
}
return max;
}
int main (int argc, char **argv) {
int array[ARR_SIZE]={1,2,3,4};
int z = groesstesElement(array, ARR_SIZE);
printf("%d\n", z);
return EXIT_SUCCESS;
}
Please note how there's no need to use a double pointer anymore.
I have a function for the Collatz Conjecture that returns an int Array but I keep getting a segmentation fault error and am not sure why.
int n=1;
int* col fuction(int x){
int *totalList;
totalList[0]=x;
while (x != 1){
if (x%2==0){
x=x/2;
}else{
x= 3* x + 1;
}
totalList[n]= x;
n++;
}
totalList[n+1]=1;
return totalList;
}
It is suppose to return the integers in a row with commas in between each number. I call it as shown below:
int *colAns;
colAns= col(num);
for (int k =0; k< n; k++){
printf("%d", colAns[k]);
if(colAns[k] != 1){
printf(",");
}
}
printf("\n");
Your issue lies within the first few lines of col_function().
int* col_fuction(int x){
int *totalList;
totalList[0]=x;
// ...
}
When the int* called totalList gets created on the stack, it takes whatever value was previously there. There's a slim chance that the pointer value will be anything even owned by the process, let alone something valid/usable.
What you need is a dynamically-allocated value that can grow as values are added to it. For this, we use malloc to allocate a pre-determined amount of memory. Because the collatz function is recursive and the number of elements cannot be determined by merely looking at it, we cannot presume to know exactly how much memory it will take, so it should grow as numbers are added to it. For this, we use realloc. What's nice about realloc is that, if the first parameter is NULL, it is guaranteed by the standard to work like malloc.
The only other thing you really need is a couple of size_t values inside of a struct in order to keep track of the current index as well as the allocated space. Something like this should be sufficient:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define CHUNK_SIZE 100
typedef struct dynarray
{
int *values;
size_t allocated, used;
} dynarray;
int dynarray_init(dynarray *d)
{
memset(d, 0, sizeof(dynarray));
return 0;
}
int dynarray_deinit(dynarray *d)
{
free(d->values);
memset(d, 0, sizeof(dynarray));
return 0;
}
int dynarray_append(dynarray *d, int val)
{
int *tmp = NULL;
size_t i;
if(d->used + 1 >= d->allocated)
{
if((tmp = (int*)realloc(d->values, (d->allocated + CHUNK_SIZE)*sizeof(int))) == NULL)
{
perror("realloc() failure");
return 1;
}
else
{
d->values = tmp;
d->allocated += CHUNK_SIZE;
}
}
d->values[d->used++] = val;
}
Use dynarray_append() to add values to the list after it's been initialized.
I create a 2-D array using malloc. When I use printf to print the array element in for loop, everything is fine. But when I want to use printf in main, these is a Segmentation fault: 11.
Could you please tell me what the problem with the following code is?
#include <stdlib.h>
#include <stdio.h>
void initCache(int **cache, int s, int E){
int i, j;
/* allocate memory to cache */
cache = (int **)malloc(s * sizeof(int *)); //set
for (i = 0; i < s; i++){
cache[i] = (int *)malloc(E * sizeof(int)); //int
for(j = 0; j < E; j++){
cache[i][j] = i + j;
printf("%d\n", cache[i][j]);
}
}
}
main()
{
int **c;
initCache (c, 2, 2);
printf("%d\n", c[1][1]); // <<<<<<<<<< here
}
Since your cache is a 2D array, it's int**. To set it in a function, pass int***, not int**. Otherwise, changes to cache made inside initCache have no effect on the value of c from main().
void initCache(int ***cache, int s, int E) {
int i, j;
/* allocate memory to cache */
*cache = (int **)malloc(s * sizeof(int *)); //set
for (i = 0; i < s; i++) {
(*cache)[i] = (int *)malloc(E * sizeof(int)); //int
for(j = 0; j < E; j++){
(*cache)[i][j] = i + j;
printf("%d\n", (*cache)[i][j]);
}
}
}
Now you can call it like this:
initCache (&c, 2, 2);
You changed a local variable, which won't effect the local variable c in main.
If you want to allocate in the function, why pass a variable? Return it from the function.
int **c = initCache(2, 2);
You could use a return, or else a *** as suggested by others. I'll describe the return method here.
initCache is creating and initializing a suitable array, but it is not returning it. cache is a local variable pointing to the data. There are two ways to make this information available to the calling function. Either return it, or pass in an int*** and use that to record the pointer value.
I suggest this:
int** initCache(int **cache, int s, int E){
....
return cache;
}
main()
{
int **c;
c = initCache (2, 2);
printf("%d\n", c[1][1]); <<<<<<<<<< here
}
====
Finally, it's very important to get in the habit of checking for errors. For example, malloc will return NULL if it has run out of memory. Also, you might accidentally as for a negative amount of memory (if s is negative). Therefore I would do:
cache = (int **)malloc(s * sizeof(int *));
assert(cache);
This will end the program if the malloc fails, and tell you what line has failed. Some people (including me!) would disapprove slightly of using assert like this. But we'd all agree it's better than having no error checking whatsoever!
You might need to #include <assert.h> to make this work.
Hi friends I am trying to assigned elements from arr2[] to a pointer p_arr and then trying to print from p_arr...
I think something is messing up, not getting expected values...
#include <stdio.h>
#include <stdlib.h>
#define MAX_ONE 9
#define MAX_TWO 9
int arr1[] = {10,20,30,40,50,67,23,47,79};
int arr2[] = {5,15,25,35,45,34,45,67,89};
int *main_arr[] = {arr1,arr2};
int main()
{
int i;
int *p_arr2;
p_arr2 = (int *)malloc(sizeof(int)*2);
for(i=0;i<MAX_ONE;i++)
{
*p_arr2++ = arr2[i];
arr2[i] = arr1[i];
}
for(i=0;i<MAX_TWO;i++)
{
printf("%d\n",*(p_arr2));
p_arr2++;
//printf("%d\t",arr2[i]);
}
system("PAUSE");
return 0;
}
p_arr2 = (int *)malloc(sizeof(int)*2);
You allocated only enough memory for 2 integers and you are trying to store MAX_ONE in this array. This results in writing beyond the allocated memory block and an Undefined behavior.
You need to allocated enough memory to store MAX_ONE elements.
p_arr2 = malloc(sizeof(int)*MAX_ONE);
^^^^^^^^^
Also, you do not need to cast the return type of malloc in C.
In addition to the allocation issues mentioned, before you start the print loop, you don't reset p_arr2 to point at the start of the array. So you're printing from uninitialized memory.
Try this. Also always try to free dynamically allocated memory
p_arr2 = malloc(sizeof(int)*MAX_ONE);
for(i=0;i<MAX_ONE;i++)
{
p_arr2[i] = arr2[i];
arr2[i] = arr1[i];
}
for(i=0;i<MAX_TWO;i++)
{
printf("%d\n",*(p_arr2 + i));;
//printf("%d\t",arr2[i]);
}
free (p_arr2);